Alex Finch
Alex Finch

Reputation: 34

I cant align this to right part of my Jpanel

I am trying to align all the buttons on the left all on top of each other, but whatever i do it always seems to stay in the center, i have tryed "c.anchor = GridBagConstraints.EAST;" but that didn't help and now im stuck please help.

    JButton Button1 = new JButton("<html> Li <center> <small> 7 <br> 3<small/> <center/> <html/> ");
    JButton Button2 = new JButton("<html> Na <center> <small> 32<br> 11<small/> <center/> <html/> ");
    JButton Button3 = new JButton("<html>K<center><small> 39 <br> 19<small/> <center/> <html/> ");



    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    int width = gd.getDisplayMode().getWidth();
    int height = gd.getDisplayMode().getHeight();

    Button1.setPreferredSize(new Dimension(50, 50));
    Button2.setPreferredSize(new Dimension(50, 50));
    Button3.setPreferredSize(new Dimension(50, 50));


    GridBagLayout layout = new GridBagLayout() ;
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;

    c.anchor = GridBagConstraints.EAST;
    setLayout(layout);
    add(Button1, c);
    add(Button2, c);
    add(Button3, c);
    add(exit);
    setSize(width, height);
    setExtendedState(JFrame.MAXIMIZED_BOTH); 
    //TODO Align to left
    setUndecorated(true);
    setLocationRelativeTo(null);

Upvotes: 0

Views: 27

Answers (1)

camickr
camickr

Reputation: 324197

c.gridx = 0;
c.anchor = GridBagConstraints.EAST;
setLayout(layout);
add(Button1, c);
add(Button2, c);
add(Button3, c);
add(exit);

Well for one thing you are adding all the components to the same cell since you use the same constraints. If you want them on different rows then you need to specify the a different "gridy" value for each component.

it always seems to stay in the center,

This is the default behaviour unless you specify a weightx/weighty value.

The easier way would be to use a JPanel with a GridLayout. The add all the button to the panel. Finally you add the panel to the frame using:

frame.add(buttonPanel, BorderLayout.LINE_START);

I suggest you start by reading the section from the Swing tutorial on Layout Managers. There are working examples of all the layout managers mentioned above.

Other problems:

  1. Variable names should not start with an upper case character.
  2. Don't use setPreferredSize() on a component. Each component should determined its own preferred size. The layout manager will then use this information.
  3. The GUI code should execute on the Event Dispatch Thread (EDT).

The Swing tutorials all follow the above standards, so download the demo code to learn from that.

Upvotes: 2

Related Questions