I have been using GridBagLayout
but turned to GroupLayout
recently. Below is a screen shot of what I have and what I need. Then the code.
What do I need to change?
I think i am supposed to be using the TRAILING
and LEADING
constants but the GUI is not responding. Could this be the reason most SO advise to people is to avoid GroupLayout
? I have been using GridBagLayout
before, which is more complex, and GroupLayout
code seems much simpler. That's why am using it. Code that I have is given below, what do I need, to have the desired effect?
public class GroupLayoutOne extends JFrame{
JLabel lbText = new JLabel("Text one");
JTextField txText = new JTextField();
JLabel lbText2 = new JLabel("Text two");
JTextField txText2 = new JTextField();
JPanel pnCompo = new JPanel();
public static void main(String[] args) {
GroupLayoutOne glx = new GroupLayoutOne();
glx.init();
glx.setVisible(true);
glx.setSize(new Dimension(400,200));
glx.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
GroupLayout gl = new GroupLayout(getContentPane());
this.getContentPane().setLayout(gl);
pnCompo.setPreferredSize(new Dimension(300,300));
pnCompo.setBorder(BorderFactory.createTitledBorder("More Components"));
gl.setHorizontalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addComponent(lbText)
.addComponent(lbText2)
.addComponent(pnCompo)
)
.addGroup(gl.createParallelGroup()
.addComponent(txText)
.addComponent(txText2)
)
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addComponent(lbText)
.addComponent(txText)
)
.addGroup(gl.createParallelGroup()
.addComponent(lbText2)
.addComponent(txText2)
)
.addComponent(pnCompo)
);
pack();
}
}
Replace your init method with the below code: BTW: Use NetBeans or Eclipse to draw swing UI. It would be much easier than writing code yourself.
GroupLayout gl = new GroupLayout(getContentPane());
this.getContentPane().setLayout(gl);
pnCompo.setPreferredSize(new Dimension(300,300));
pnCompo.setBorder(BorderFactory.createTitledBorder("More Components"));
gl.setHorizontalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addGroup(gl.createSequentialGroup().addComponent(lbText)
.addComponent(txText))
.addGroup(gl.createParallelGroup()
.addGroup(gl.createSequentialGroup().addComponent(lbText2)
.addComponent(txText2))
.addComponent(pnCompo))
)
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addGroup(gl.createParallelGroup()
.addComponent(lbText)
.addComponent(txText))
.addGroup(gl.createParallelGroup().addComponent(lbText2)
.addComponent(txText2)
)
.addComponent(pnCompo)
);
pack();