Reputation: 49
The problem I've been having for a while is that whenever I add a JButton to a JPanel, any other JButton that I had on was shifted in that direction.
Here is the first code:
//imports
import java.awt.*;
import javax.swing.*;
public class Example {
public static void main(String[] args) {
// Create the frame and panel and the Grid Bag Constraints
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Create ONE JButton
JButton button1 = new JButton("Button1");
// Set the frame's properties
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.setVisible(true);
// Set Basic Grid Bag Constraints settings.
c.gridx = 0;
c.gridy = 0;
// Set the Insets
c.insets = new Insets(0, 0, 0, 0);
// Add the Grid Bag Constraints and button1 the panel
panel.add(button1, c);
}
}
Everything seems to working right? Well if we add a second button:
//imports
import java.awt.*;
import javax.swing.*;
public class Example {
public static void main(String[] args) {
// Create the frame and panel and the Grid Bag Constraints
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Create TWO JButtons
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
// Set the frame's properties
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.setVisible(true);
// Set Basic Grid Bag Constraints settings.
c.gridx = 0;
c.gridy = 0;
// Set the Insets
c.insets = new Insets(0, 0, 0, 0);
// Add the Grid Bag Constraints and button1 the panel
panel.add(button1, c);
// Set the Insets
c.insets = new Insets(500, 0, 0, 0);
// Add the Grid Bag Constraints and button2 the panel
panel.add(button2, c);
}
}
Then button1 moves down towards button2. Does anyone know why and/or a fix for it?
EDIT: What I am asking, is how do you add another button without moving the other buttons.
Upvotes: 0
Views: 153
Reputation: 324108
I don't know what your intent is. You only state it doesn't do what you expect. So I can't give you an exact solution.
In any case start by reading the section from the Swing tutorial on How to Use GridBagLayout for working examples using a GridBagLayout
.
I see two issues:
You never change the gridx/y values. Both components are added to grid (0, 0) which is not how the GridBagLayout
should work. Every component needs to be added to a different cell.
The Insets
value of (500, ....) seems very big.
Upvotes: 0