Line up swing components by edges
Posted
by
rasen58
on Stack Overflow
See other posts from Stack Overflow
or by rasen58
Published on 2012-11-09T02:44:18Z
Indexed on
2012/11/09
5:01 UTC
Read the original article
Hit count: 160
Is it possible to line up swing components? The components are in separate panels which both use flow layout. These two panels are in another panel which is using a grid layout.
As you can see there is a subtle difference and I find it annoying. I know that all of the jlabels [the rectangles in blue/purple all have the same size, so i think it might be because of the '+' and '*', but I'm not sure because the left sides of the first two boxes aren't lined up.
the panels
JPanel panel2 = new JPanel(new GridLayout(4, 1));
JPanel panel2a = new JPanel(new FlowLayout());
JPanel panel2b = new JPanel(new FlowLayout());
the first two rectangles (purple)
add1 = new JLabel("", JLabel.CENTER);
add1.setTransferHandler(new TransferHandler("text"));
add1.setBorder(b2);
add2 = new JLabel("", JLabel.CENTER);
add2.setTransferHandler(new TransferHandler("text"));
add2.setBorder(b2);
the two blue rectangles
textFieldA = new JTextField();
textFieldA.setHorizontalAlignment(JTextField.CENTER);
textFieldA.setEditable(false);
textFieldA.setBorder(new LineBorder(Color.blue));
textFieldM = new JTextField();
textFieldM.setHorizontalAlignment(JTextField.CENTER);
textFieldM.setEditable(false);
textFieldM.setBorder(new LineBorder(Color.blue));
the + and *
opA = new JLabel("+", JLabel.CENTER);
opS = new JLabel("*", JLabel.CENTER);
Showing that the rectangles are the same size
Dimension d = card1.getPreferredSize();
int width = d.width + 100;
int height = d.height + 50;
add1.setPreferredSize(new Dimension(width, height));
add2.setPreferredSize(new Dimension(width, height));
mult1.setPreferredSize(new Dimension(width, height));
mult2.setPreferredSize(new Dimension(width, height));
textFieldA.setPreferredSize(new Dimension(width, height));
textFieldM.setPreferredSize(new Dimension(width, height));
Adding to the panels
panel2a.add(add1);
panel2a.add(opA);
panel2a.add(add2);
panel2a.add(enterA);
panel2a.add(textFieldA);
panel2c.add(mult1);
panel2c.add(opM);
panel2c.add(mult2);
panel2c.add(enterM);
panel2c.add(textFieldM);
panel2.add(panel2a);
panel2.add(panel2c);
© Stack Overflow or respective owner