在GridBagLayout中的组件之间放置空格

时间:2017-07-12 18:11:01

标签: java swing layout-manager gridbaglayout

我有JPanel,其中包含两个JToggleButtons。该面板有一个GridBagLayout,有1行和2列。按钮位于同一行,但列不同。

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);
        }
}

我希望能够控制按钮之间的间距,但是切换c.gridwidthc.weightx并不会给我带来结果。将c.wightx设置为0.0会导致按钮彼此太靠近,而除零之外的任何内容都会导致它们距离太远,c.widthx=0.9c.widthx=0.1之间的距离没有差异。我做错了什么?

1 个答案:

答案 0 :(得分:3)

尝试制作Insets变量,每次点击按钮时int都会增加。代码如下:

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); 

        //...
    }