Placing buttons in a specified location using swing in java
Asked Answered
B

2

8

I am trying to learn how to make JAVA programs and I am working with Swing. I am trying to place a button in the top left corner of the window and it keeps going to the top center.

public void createGUI(){
    JFrame frame = new JFrame("My Project");
    frame.setDefaultCloseOperation(3);
    frame.setSize(400, 350);
    frame.setVisible(true);

    JPanel panel = new JPanel();

    frame.add(panel);

    addButtonGUI(panel, new JButton(), "test", 1, 1);
}

public void addButtonGUI(JPanel panel, JButton button, String text, int x, int y){
    GridBagConstraints gbc = new GridBagConstraints();
    button.setText(text);
    button.setEnabled(true);
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = 2;
    gbc.weightx = 1.0D;
    gbc.fill = 2;
    panel.add(button, gbc);
}

What am I doing wrong or is there a better way to do this? Please help

Bookstall answered 13/12, 2012 at 19:55 Comment(1)
frame.setDefaultCloseOperation(3); Don't use magic numbers. The J2SE has descriptively named constants for these values.Arlie
D
7

You need to set the layout of the JPanel to GridBagLayout to use GridBagConstraints:

JPanel panel = new JPanel(new GridBagLayout());

Also as you only have one effective 'cell' you need to use an anchor and set weighty for the JButton to allow movement in the Y-axis.

gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weighty = 1.0;

Also I would set the fill setting to NONE:

gbc.fill = GridBagConstraints.NONE;

so that the button does not occupy the full width of the panel. (2 = HORIZONTAL fill).

Danner answered 13/12, 2012 at 20:4 Comment(0)
S
2

instead of

addButtonGUI(panel, new JButton(), "test", 1, 1);
}

what would happen if you used

addButtonGUI(panel, new JButton(), "test", 0, 0);
}
Shoulder answered 13/12, 2012 at 20:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.