Placing buttons in a specific place using swing in java

I am trying to learn how to make JAVA programs and I am working with Swing. I try to place the button in the upper left corner of the window, and it continues to go to the upper 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

+8
java layout-manager swing jpanel gridbaglayout
source share
2 answers

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

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

Also, since you only have one effective cell, you need to use snapping and set weighty for JButton to allow movement along the Y axis.

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

I would also set fill to NONE :

 gbc.fill = GridBagConstraints.NONE; 

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

+7
source share

instead

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

what happens if you used

 addButtonGUI(panel, new JButton(), "test", 0, 0); } 
+2
source share

All Articles