I am new to Java Swing I want to develop an POS application which is like this image:
To develop this application I am using Eclipse, I have created JPanel which is shown by numbers e.g(1, 2) in image. At no 3 I have added JscrollPan which contain JPanel, now I want to do here when I click a button from panel no 2 that should add new buttons in panel no 3 dynamically and at that time I want to show only three buttons at each line and scroll should be activate only vertically when needed. But I am not able to do that, because when I write scrollPanel.setPreferredSize(new Dimension(2, 3)); vertical scroll cannot work. My Code is here:
public class WelcomeUI extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WelcomeUI frame = new WelcomeUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public WelcomeUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setUndecorated(true);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
header = new JPanel();
header.setForeground(Color.BLUE);
FlowLayout fl_header = (FlowLayout) header.getLayout();
fl_header.setAlignment(FlowLayout.RIGHT);
fl_header.setVgap(40);
fl_header.setHgap(0);
header.setBackground(Color.BLUE);
contentPane.add(header, BorderLayout.NORTH);
footer = new JPanel();
FlowLayout flowLayout = (FlowLayout) footer.getLayout();
flowLayout.setVgap(10);
footer.setBackground(Color.BLUE);
contentPane.add(footer, BorderLayout.SOUTH);
panel_2 = new JPanel();
panel_2.setBackground(Color.BLUE);
contentPane.add(panel_2, BorderLayout.WEST);
JButton btnSelectRestaurant = new JButton("Select Restaurant");
btnSelectRestaurant.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createDynamicButton(e);
}
});
JButton btnNewButton = new JButton("Select Steward");
JButton btnNewButton_1 = new JButton("Select Table");
JButton btnNewButton_2 = new JButton("Misc keys");
GroupLayout gl_panel_2 = new GroupLayout(panel_2);
gl_panel_2.setHorizontalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGap(19)
.addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
.addComponent(btnNewButton, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addComponent(btnSelectRestaurant, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnNewButton_1, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addComponent(btnNewButton_2, Alignment.TRAILING, 0, 0, Short.MAX_VALUE))
.addContainerGap())
);
gl_panel_2.setVerticalGroup(
gl_panel_2.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel_2.createSequentialGroup()
.addGap(26)
.addComponent(btnSelectRestaurant, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNewButton_1, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnNewButton_2, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
.addContainerGap(438, Short.MAX_VALUE))
);
gl_panel_2.setAutoCreateContainerGaps(true);
gl_panel_2.setAutoCreateGaps(true);
panel_2.setLayout(gl_panel_2);
panel_3 = new JPanel();
FlowLayout flowLayout_2 = (FlowLayout) panel_3.getLayout();
flowLayout_2.setHgap(250);
contentPane.add(panel_3, BorderLayout.EAST);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
scrollPanel = new JPanel();
scrollPanel.setPreferredSize(new Dimension(2, 3));
scrollPane.setViewportView(scrollPanel);
}
protected void createDynamicButton(ActionEvent e) {
JButton dynButton = new JButton("My Button");
dynButton.setPreferredSize(new Dimension(300, 200));
scrollPanel.add(dynButton);
scrollPanel.validate();
scrollPanel.revalidate();
}
private JPanel header;
private JPanel footer;
private JPanel panel_2;
private JPanel panel_3;
private JPanel scrollPanel;
private JScrollPane scrollPane;
}
So, please tell me where I am doing wrong. Thanks in advance.
Focusing on panel 3, consider the following:
Give the panel a GridLayout(0, 3), which specifies an arbitrary number rows in three columns.
Implement the Scrollable interface, and let getPreferredScrollableViewportSize() return a a Dimension that is a multiple of the button height.
As each button is added, give it a suitable Action.
When adding a button, revalidate() the panel and repaint() it.
I got the answer, actually the problem is, I have set maximum size for panel and all dynamically generated buttons placed at single line, that are added till max size not encountered, but functions cannot communicate other one hence we need to change size dynamically and that will happen by modifying FlowLayout interface.
you can use modified layout rather than FlowLayout.
Related
I am trying to layout my JPanel such that:
The information label is at the top,
The text area is directly below, this and the info label go across (horizontally) the entire panel,
Below the text from left to right (equally spaced) are the config, save and then clear buttons,
Below those is the success/failure label (central, under the save button) and the home button (right, under the clear button).
I have tried many combinations and used other stack answers but cannot get it right, something about group layout I can't get my head around!
import javax.swing.*;
public class JFrameTest {
private static JFrame mainApp;
private static JPanel mainPanel;
public JFrameTest() {
mainApp = new JFrame("Application");
mainApp.setSize(640, 480);
mainApp.setLocationRelativeTo(null);
mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainApp.add(mainPanel());
mainApp.setVisible(true);
}
private JPanel mainPanel() {
JFrame.setDefaultLookAndFeelDecorated(true);
mainPanel= new JPanel();
mainPanel.setSize(600,450);
Container container = mainApp.getContentPane();
JLabel labelInfo = new JLabel("add necessary information here");
JLabel labelSOrF = new JLabel("Success/Failure");
// labelSOrF.setVisible(false);
JTextArea textArea = new JTextArea();
JButton configButton= new JButton("config");
JButton saveButton= new JButton("save");
JButton clearButton= new JButton("clear");
JButton homeButton= new JButton("Home");
GroupLayout layout = new GroupLayout(container);
container.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(configButton)
.addGroup(layout.createParallelGroup()
.addComponent(saveButton)
.addComponent(labelSOrF, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup()
.addComponent(clearButton)
.addComponent(homeButton)
.addComponent(labelInfo)
.addComponent(textArea, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
)))
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(labelInfo)
.addComponent(textArea, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup()
.addGroup(layout.createSequentialGroup()
.addComponent(configButton)
.addComponent(saveButton)
.addComponent(buttonClear))
.addGroup(layout.createParallelGroup()
.addComponent(labelSOrF, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(homeButton)))
);
edit - added code
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
GroupLayout was designed for GUI builders. No human being will deliberately use a GroupLayout. It's too hard to understand and as you've discovered, maintain.
Here's a GUI that meets your requirements.
Swing was designed to be constructed from the inside out. You layout the Swing components and let the JPanels and the JFrame size themselves. You don't start with the JFrame and fit all the Swing components.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
I created a main JPanel with three subordinate JPanels. To construct a complex GUI, you nest simple JPanels.
I added the Swing components to each JPanel in column, row order. That helps me to organize the code and makes it easier for readers of your code to understand the code.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class JFrameTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JFrameTest());
}
#Override
public void run() {
JFrame mainApp = new JFrame("Application");
mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainApp.add(createMainPanel(), BorderLayout.CENTER);
mainApp.pack();
mainApp.setLocationRelativeTo(null);
mainApp.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(createTitlePanel());
panel.add(createTextAreaPanel());
panel.add(createButtonPanel());
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JLabel labelInfo = new JLabel("add necessary information here");
panel.add(labelInfo);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JTextArea textArea = new JTextArea(5, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scrollPane);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3, 20, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton configButton = new JButton("config");
panel.add(configButton);
JButton saveButton = new JButton("save");
panel.add(saveButton);
JButton clearButton = new JButton("clear");
panel.add(clearButton);
JLabel dummy = new JLabel(" ");
panel.add(dummy);
JLabel labelSOrF = new JLabel("Success/Failure");
panel.add(labelSOrF);
JButton homeButton = new JButton("Home");
panel.add(homeButton);
return panel;
}
}
Here's my code:
LoginPage:
public class LoginPage {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
LoginPage window = new LoginPage();
window.frmLoginPage.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private JFrame frmLoginPage;
private JPasswordField passwordField;
private JTextField textField;
/**
* Create the application.
*/
public LoginPage() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmLoginPage = new JFrame();
frmLoginPage.setTitle("Login Page");
frmLoginPage.getContentPane().setBackground(new Color(100, 149, 237));
frmLoginPage.setBounds(100, 100, 742, 597);
frmLoginPage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmLoginPage.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3, true));
panel.setBackground(Color.WHITE);
panel.setBounds(131, 106, 459, 288);
frmLoginPage.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblUserLogin = new JLabel("User Login");
lblUserLogin
.setIcon(new ImageIcon(LoginPage.class.getResource("/javax/swing/plaf/metal/icons/ocean/info.png")));
lblUserLogin.setFont(new Font("Trebuchet MS", Font.PLAIN, 34));
lblUserLogin.setHorizontalAlignment(SwingConstants.CENTER);
lblUserLogin.setBounds(114, 16, 243, 39);
panel.add(lblUserLogin);
JLabel lblUserId = new JLabel("User ID:");
lblUserId.setBounds(52, 75, 90, 20);
panel.add(lblUserId);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(52, 140, 90, 20);
panel.add(lblPassword);
passwordField = new JPasswordField();
passwordField.setBounds(52, 176, 282, 26);
panel.add(passwordField);
textField = new JTextField();
textField.setBounds(52, 98, 283, 26);
panel.add(textField);
textField.setColumns(10);
JButton btnLogIn = new JButton("Log In");
btnLogIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new SemesterPage();
frmLoginPage.setVisible(false);
}
});
btnLogIn.setBounds(52, 219, 115, 29);
panel.add(btnLogIn);
JButton btnRegister = new JButton("Register");
btnRegister.setBounds(179, 219, 115, 29);
panel.add(btnRegister);
}
}
And when the button "Log In" gets clicked, a new window within this class is supposed to pop up:
SemesterPage:
public class SemesterPage {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
SemesterPage window = new SemesterPage();
window.frmControlPanel.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private JFrame frmControlPanel;
/**
* Create the application.
*/
public SemesterPage() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmControlPanel = new JFrame();
frmControlPanel.setTitle("Control Panel");
frmControlPanel.setBounds(100, 100, 1000, 1000);
frmControlPanel.getContentPane().setBackground(new Color(100, 149, 237));
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
JPanel panel_2 = new JPanel();
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
GroupLayout groupLayout = new GroupLayout(frmControlPanel.getContentPane());
groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
.createSequentialGroup().addContainerGap()
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 637, GroupLayout.PREFERRED_SIZE).addGap(30)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap()));
groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup().addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 793, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 370,
GroupLayout.PREFERRED_SIZE)
.addGap(18).addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 412,
GroupLayout.PREFERRED_SIZE)))
.addContainerGap(97, Short.MAX_VALUE)));
frmControlPanel.getContentPane().setLayout(groupLayout);
frmControlPanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frmControlPanel.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmLogOut = new JMenuItem("Log Out");
mnFile.add(mntmLogOut);
}
}
The problem is, the window does not pop up. Nothing happens when the button gets clicked. I have a feeling that when I call "new SemesterPage()", the constructor within my SemesterPage class does not start a JFrame. How would I go about fixing this?
Thank you very much!
You create a new instance of SemesterPage but never make it visible...
Your SemesterPage is going to need a method which will allow the caller to instruct it that it would like to make the instance of JFrame which it creates visible
Maybe something like...
public class SemesterPage {
private JFrame frmControlPanel;
//...
public void setVisible(boolean v) {
frmControlPanel.setVisible(v);
}
Having said that, you might want to reconsider your design slightly...
Start by having a look at The Use of Multiple JFrames, Good/Bad Practice?.
Then How to Make Dialogs and How to Use CardLayout for some ideas on alternatives
You might also consider having a look at Model-View-Controller, for example
I want to generate multiple panels (with title, desc and detail button), this is the general structure:
But when I put this code in a for loop it always adds the last item.
Panel panel_1 = new Panel();
panel_1.setBounds(23, 134, 378, 208);
JLabel lblNewLabel_2 = new JLabel("desc");
lblNewLabel_2.setBounds(0, 69, 189, 69);
JButton btnNewButton_2 = new JButton("Details");
btnNewButton_2.setBounds(104, 139, 189, 69);
panel_1.setLayout(null);
JLabel lblPrv = new JLabel("title");
lblPrv.setBounds(104, 0, 189, 69);
panel_1.add(lblPrv);
panel_1.add(lblNewLabel_2);
JLabel label_1 = new JLabel("");
label_1.setBounds(0, 69, 189, 69);
panel_1.add(label_1);
panel_1.add(btnNewButton_2);
Any suggestion?
Here is an example of how to place multiple panels next to each other:
public class Example extends JFrame {
Example() {
setLayout(new FlowLayout());
for (int i = 0; i < 4; i++)
add(new MyPanel());
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
class MyPanel extends JPanel {
MyPanel() {
setLayout(new BorderLayout());
add(new JLabel("title", SwingConstants.CENTER), BorderLayout.PAGE_START);
add(new JLabel("<html>WWWWWW WWWWWWW<p>WWWWWWWWW<p>RRRRRRR RRRRR RRRRRRR"));
add(new JButton("Details"), BorderLayout.PAGE_END);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Example());
}
}
You should pick the layout managers best suited for your situation.
Hi i am trying to make java desktop application where i am using multiple jlabel i want to give little spaces between every label
how can i achieve this
here is my code
public class Second extends javax.swing.JFrame {
JLabel label=new JLabel();
/**
* Creates new form Second
*/
public Second() {
this.getContentPane().setBackground(new java.awt.Color(255, 140, 0));
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setUndecorated(true);
JButton print= new JButton();
print.setBackground(new java.awt.Color(153, 153, 0));
print.setOpaque(true);
print.setBounds(525,1282,130,85);
print.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
print.setForeground(new java.awt.Color(255,255,255));
print.setText("Print");
this.add(print);
JButton home= new JButton();
home.setBackground(new java.awt.Color(153, 153, 0));
home.setOpaque(true);
home.setBounds(640,1282,130,85);
home.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
home.setForeground(new java.awt.Color(255, 255,255 ));
home.setText("Home");
this.add(home);
int Height = 134;
int a=100;
ArrayList<JLabel> label = new ArrayList<JLabel>();
for(int i=0;i<23;i++){
JLabel j = new JLabel();
j.setBackground(new java.awt.Color(255, 140, 255));
j.setOpaque(true);
j.setBounds(5,Height,378,50);
j.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
j.setForeground(new java.awt.Color(128, 128, 128));
j.setText("Case Item CourtNo ");
LineBorder line = new LineBorder(Color.blue, 2, true);
j.setBorder(line);
this.add(j);
label.add(j);
JLabel j1 = new JLabel();
j1.setBackground(new java.awt.Color(255, 140, 0));
j1.setOpaque(true);
j1.setBounds(390,Height,768,50);
j1.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
j1.setForeground(new java.awt.Color(128, 128, 128));
j1.setText("Case Item CourtNo ");
this.add(j1);
label.add(j1);
Height = Height +50;
a=a+10;
}
initComponents();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g3 = (Graphics2D) g;
BasicStroke bs = new BasicStroke(2);
Line2D lin1 = new Line2D.Float(386, 100, 386, 1282);
Line2D lin = new Line2D.Float(0, 1283, 768, 1283);
Line2D line3=new Line2D.Float(400,1284,400,1364);
g3.setStroke(bs);
g3.setColor(Color.white);
g3.draw(lin1);
g3.draw(lin);
g3.draw(line3);;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Second().setVisible(true);
}
});
}}
My new code
public class Testing1 extends javax.swing.JFrame {
public Testing1() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
panel.setLocation(100, 100);
//panel.setLayout(null);
this.add(panel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
initComponents();
}
private JPanel createPanel() {
jPanel1 = new JPanel(new GridLayout(0, 1, 10, 5));
EmptyBorder panelBorder = new EmptyBorder(10, 10, 10, 10);
jPanel1.setBorder(panelBorder);
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i <12; i++) {
JLabel label = new JLabel("Label" + i);
label.setBorder(compound);
// label.setBounds(13, 100, 100, 50);
jPanel1.add(label);
}
return jPanel1;
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(204, 0, 153));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 306, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 243, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 94, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Testing1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
updated
Thanks in advance
"How to give spaces between jlabel?"
setBounds and null layouts: no; Use EmptyBorders: YES!; Use LayoutManagers: YES!
"how can i use this can u explain little bit "
Use can use the default FlowLayout of the containing JPanel (or in this case set the gaps of the FlowLayout)
FlowLayout constructor:
public FlowLayout(int align,
int hgap,
int vgap)
align - the alignment value
hgap - the horizontal gap between components and between the components and the borders of the Container
vgap - the vertical gap between components and between the components and the borders of the Container
Example
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 5);
for (int i = 0; i < 10; i++) {
panel.add(new JLabel("Label" + i));
}
You could use EmptyBorder
EmptyBorder constructor
public EmptyBorder(int top,
int left,
int bottom,
int right)
top - the top inset of the border
left - the left inset of the border
bottom - the bottom inset of the border
right - the right inset of the border
Example
JPanel panel = new JPanel();
for (int i = 0; i < 10; i++) {
JLabel label = new JLabel("Label" + i);
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
label.setBorder(border);
panel.add(label);
}
If you want to use a LineBorder and an EmptyBorder for margins, you can use a CompoundBorder
A composite Border class used to compose two Border objects into a single border by nesting an inside Border object within the insets of an outside Border object. For example, this class may be used to add blank margin space to a component with an existing decorative border:
CompoundBorder Example
JPanel panel = new JPanel();
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i < 10; i++) {
JLabel label = new JLabel("Label" + i);
label.setBorder(compound);
panel.add(label);
}
There is an abundant number possibilities. Choose your flavor. The whole point it no not try and set size and position to everything, and make use of layout managers and borders and gaps for sizing, spacing etc.
Learn to use the different layout managers at Laying out Components Within a Container
Full example using CompoundBorder and GridLayout(int rows, int cols, int hgap, int vgap)
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CompoundBorderDemo {
public CompoundBorderDemo() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel = new JPanel(new GridLayout(5, 5, 10, 10));
EmptyBorder panelBorder = new EmptyBorder(10, 10, 10, 10);
panel.setBorder(panelBorder);
EmptyBorder border = new EmptyBorder(5, 20, 5, 20);
LineBorder line = new LineBorder(Color.blue, 2, true);
CompoundBorder compound = new CompoundBorder(line, border);
for (int i = 0; i < 25; i++) {
JLabel label = new JLabel("Label" + i);
label.setBorder(compound);
panel.add(label);
}
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CompoundBorderDemo();
}
});
}
}
Try using layouts like GridLayout instead of setting bounds to every label.
it is the simplest solution for your problem.Grid Layout May suit you better.
refer the links below for that..
GRID LAYOUT
I have this class which creates a grid:
class GridPane extends JPanel{
public GridPane(int row,int col){
setLayout(new GridLayout(row,col));
setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
for (int i =1; i<=(row*col); i++)
{
JPanel pan = new JPanel();
pan.setBackground(Color.RED);
pan.setPreferredSize(new Dimension(3,3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(pan);
}
}
And this which sets up the empty main frame with the group layout:
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGap(0, 440, Short.MAX_VALUE)
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGap(0, 268, Short.MAX_VALUE)
);
contentPane.setLayout(gl_contentPane);
}
I am not very experienced with SWING and I have been trying to add a GridPane object to the Right of the Main Frame for some time. It keeps telling me something like :
java.lang.IllegalStateException: GridPane[,0,0,0x0,invalid,layout=java.awt.GridLayout,alignmentX=0.0,alignmentY=0.0,border=javax.swing.border.EmptyBorder#6ba7508a,flags=9,maximumSize=,minimumSize=,preferredSize=] is not attached to a vertical/horizontal group
Does anyone know what is going on? What should I do to accomplish what I need? Sorry for posting lots of code. Thanks for the help.
I would suggest that in this case you make use of BorderLayout.
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(pan, BorderLayout.LINE_END);
Here is the full code. I hope this is what you are looking for.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
GridPane gp = new GridPane(5, 5);
frame.add(gp, BorderLayout.EAST);
frame.setVisible(true);
frame.setSize(250, 250);
}
}
class GridPane extends JPanel {
public GridPane(int row, int col) {
setLayout(new GridLayout(row, col));
setPreferredSize(new Dimension(125, 125));
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
for (int i = 1; i <= (row * col); i++) {
JPanel pan = new JPanel();
pan.setBackground(Color.RED);
pan.setPreferredSize(new Dimension(3, 3));
pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(pan);
}
}
}
Useful links:
A Visual Guide to Layout Managers
How to Use BorderLayout
How to Use GroupLayout