Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line up swing components by edges

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.

image

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);
like image 203
rasen58 Avatar asked Dec 17 '25 23:12

rasen58


1 Answers

AFAIU this could be achieved using GroupLayout. This layout would require 5 horizontal groups and 2 vertical groups.

GroupLayout vertical & horizontal groups

See How to Use GroupLayout for examples (including discussion of that image).

See also this answer for an MCVE.

like image 125
Andrew Thompson Avatar answered Dec 19 '25 12:12

Andrew Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!