I have a JPanel
that contains two JToggleButtons
. The panel has a GridBagLayout
and has 1 row and 2 columns. Buttons are located in the same row, but different columns.
class UserInterfacePanel extends JPanel {
private JToggleButton startButton;
private JToggleButton stopButton;
public UserInterfacePanel() {
setup();
}
private void setup() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setupButtons();
//setupButtonsActions();
c.insets=new Insets(3,3,3,3);
c.weightx=0.5; //c.weightx=0.0;
c.weighty=0.5; //c.weighty=0.5;
c.gridx=0;
c.gridy=0;
add(startButton, c);
c.gridx=1;
c.gridy=0;
add(stopButton, c);
}
private void setupButtons() {
startButton=new JToggleButton(iconStartButton);
stopButton=new JToggleButton(iconStopButton);
}
public class UserInterface extends JFrame {
public static void main(String[] args) {
run();
}
public UserInterface() {
setup();
}
private void setup() {
width=800;
height=600;
panel=new UserInterfacePanel();
getContentPane().add(panel);
setSize(width, height);
}
public static void run() {
UserInterface gui=new UserInterface();
gui.setVisible(true);
}
}
I want to be able to control the spacing between the buttons, but changin c.gridwidth
or c.weightx
doesn't give me results. Setting c.wightx
to 0.0 results in the buttons being too close to each other, while anything other than zero results in them being too far away, with no difference in distance between c.widthx=0.9
and c.widthx=0.1
. What am I doing wrong?
Try making an Insets
variable, with int
s that increase every time a button is clicked. Code below:
public class UserInterfacePanel extends JPanel {
private JToggleButton startButton;
private JToggleButton stopButton;
private int top = 3, left = 3, bottom = 3, right = 3;
private Insets i = new Insets(top, left, bottom, right);
public UserInterfacePanel() {
setup();
}
private void setup() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setupButtons();
setupButtonsActions();
c.insets = i;
c.weightx=0.5; //c.weightx=0.0;
c.weighty=0.5; //c.weighty=0.5;
c.gridx=0;
c.gridy=0;
add(startButton, c);
c.gridx=1;
c.gridy=0;
add(stopButton, c);
JButton b1 = new JButton("+1");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
i = new Insets(top+1, left+1, bottom+1, right+1);
c.insets = i;
repaint();
}
});
add(b1, BorderLayout.SOUTH);
//...
}