I want to have the following layout:
(i.e. jbutton and jlabel are placed at jpanel, jbutton is centered and jlabel goes just after it. Layout should be able to resize. Edit: Size of jbutton and jlabel is constant during resizing.)
I thought about the following:
Use appropriate layout manager. I don't know one. I can add jbutton and jlabel to another jpanel and add this new jpanel to center of large jpanel but in that case jbutton won't be centered.
Edit: I tried to use this proposal: (proposal was edited and code is correct now there)
public class MainFrame extends JFrame { public static void main(String[] args) { new MainFrame(); }
} }public MainFrame() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; add(new JPanel(), c); c.gridx = 1; c.weightx = 0; c.anchor = GridBagConstraints.CENTER; add(new JButton("Button"), c); c.gridx = 2; c.weightx = 1; c.anchor = GridBagConstraints.WEST; add(new JLabel("Label"), c); pack(); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE);
But it produces the following output where button isn't centered:
Add jbutton and jlabel to jpanel. Add
ComponentListener
to jpanel and overridecomponentResized
there. Overriden method will look like:public void componentResized(ComponentEvent e) { int x = button.getX() + button.getWidth() + 3; int y = button.getY(); label.setLocation(new Point(x, y)); }
JButton's position will be chosen when resizing automatically by layout manager and jlabel's position by this method. But
componentResized
will be invoked only after resizing will complete. So in process of resizing jlabel's position will be defined by layout manager which isn't desired.- Add jbutton to content pane and jlabel to glass pane. But I'll have the same problem with resizing as in previous case.
How can I achieve this layout?