开发者

GridBagLayout multiple buttons + border

开发者 https://www.devze.com 2023-03-28 06:46 出处:网络
I\'m trying to use GridBagLayout for 10 (3x3 + 1) JButtons inside a JPanel using BoxLayout. But what ever I do with glueboxes or similarly the GridBagLayout JPanel takes up all the extra space in the

I'm trying to use GridBagLayout for 10 (3x3 + 1) JButtons inside a JPanel using BoxLayout.

But what ever I do with glueboxes or similarly the GridBagLayout JPanel takes up all the extra space in the BoxLayout. I'm probably missing something or is this not possible to do?

One solution I have used is to push the buttons up with a expanding element inside the gridbaglayout. This puts the buttons in the right place but the border box appear to big.

Here follows my example code:

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GridBagLayoutTest extends JFrame {

    public GridBagLayoutTest(){
        super();
        this.setTitle("JVectorView");
        this.setSize(300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = this.getContentPane();
        content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
        content.add(new JLabel("Hello!"));
        content.add(new Controls());
        content.add(Box.createGlue());
        this.setVisible(true);
    }


    private class Controls extends JPanel{
        private static final int WIDTH = 3, HEIGHT = 3;

        public Controls(){
            GridBagConstraints constraints = new GridBagConstraints();

            //this.setBorder(BorderFactory.createLineBorder(Color.red));
            this.setBorder(BorderFactory.createTitledBorder("Some stuff"));
            constraints.fill = GridBagConstraints.NONE;
            this.setL开发者_如何学Pythonayout(new GridBagLayout());
            for(int row = 0; row < HEIGHT; row++){
                for(int col = 0; col < WIDTH; col++){
                    constraints.gridx = col;
                    constraints.gridy = row;
                    this.add(new JButton("B"+(col+row*WIDTH)), constraints);

                }
            }
            constraints.gridx = 1;
            constraints.gridy = 3;
            this.add(new JButton("B"+(10)), constraints);
        }
    }

    public static void main(String[] args) {
        new GridBagLayoutTest();
    }

}

I would like the border to be tight around the buttons. Is it at all possible to get gridbaglayout to collapse in on it's content or does it always force fill the panels?


JPanel p=new JPanel(new FlowLayout());
p.add(new Controls());
content.add(p);
0

精彩评论

暂无评论...
验证码 换一张
取 消