I'm trying to place one label and one textfield on one row and on the second row another label and textfield. The problem is that the second pair of JComponents go on the first line too. I'm using first a GridLayout(2,1) where in the first row I place a JPanel with GridBagLayout with these two pairs and on the second row I use a JPanel with GridBagLayout where I place a submit button.
JDialog dialog;
JLabel name;
JLabel rating;
dialog = new JDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setSize(300, 350);
//dialog.setResizable(false);
dialog.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(2,1));
dialog.getContentPane().add(mainPanel);
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
mainPanel.add(firstPanel);
name = new JLabel("Name:");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
firstPanel.add(name);
JTextField label1 = new JTextField(10);
c.gridx = 1;
c.gridy = 0;
firstPanel.add(label1);
rating = new JLabel("Rating:");
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
firstPanel.add(rating);
JTextField label2 = new JTextField(10);
c.gridx = 1;
c.gridy = 1;
firstPanel.add(label2);
JPanel submit = new JPanel();
submit.setLayout(new GridBagLayout());
mainPanel.add(submit);
JButton buton = new JButton("Submit");
submit.add(buton);
dialog.pack();
dialog.setVisible(true);
You haven't supplied the GridBagConstraints
to the container when adding your components...
firstPanel.add(name);
Instead, use something more like
firstPanel.add(name, c);
This will pass the component and constraints to the GridLayoutManager
See How to use GridBagLayout for more details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.