在swing组布局中手动添加自定义组件

时间:2011-12-25 15:23:07

标签: java swing windowbuilder

我有这个创建网格的类:

 class GridPane extends JPanel{ 

    public GridPane(int row,int col){

      setLayout(new GridLayout(row,col));

      setBorder(BorderFactory.createEmptyBorder(1,1,1,1));

      for (int i =1; i<=(row*col); i++)
      {
         JPanel pan = new JPanel();
         pan.setBackground(Color.RED);
         pan.setPreferredSize(new Dimension(3,3));
         pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
         add(pan);
       } 
} 

这就是用组布局设置空主框架:

public MainFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGap(0, 440, Short.MAX_VALUE)
    );
    gl_contentPane.setVerticalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGap(0, 268, Short.MAX_VALUE)
    );
    contentPane.setLayout(gl_contentPane);
}

我对SWING不太熟悉,并且我一直试图将GridPane对象添加到主框架的右侧一段时间。它一直告诉我类似的东西:

  

java.lang.IllegalStateException:GridPane [,0,0,0x0,invalid,layout = java.awt.GridLayout,alignmentX = 0.0,alignmentY = 0.0,border = javax.swing.border.EmptyBorder @ 6ba7508a,flags = 9,maximumSize =,minimumSize =,preferredSize =]未附加到垂直/水平组

有谁知道发生了什么事?我该怎么做才能完成我的需要?很抱歉发布了大量代码。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

我建议您在这种情况下使用BorderLayout

contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());

contentPane.add(pan, BorderLayout.LINE_END);

这是完整的代码。我希望这就是你要找的东西。

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        GridPane gp = new GridPane(5, 5);

        frame.add(gp, BorderLayout.EAST);

        frame.setVisible(true);
        frame.setSize(250, 250);
    }
}

class GridPane extends JPanel {

    public GridPane(int row, int col) {

        setLayout(new GridLayout(row, col));
        setPreferredSize(new Dimension(125, 125));
        setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

        for (int i = 1; i <= (row * col); i++) {
            JPanel pan = new JPanel();
            pan.setBackground(Color.RED);
            pan.setPreferredSize(new Dimension(3, 3));
            pan.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            add(pan);
        }
    }
}

有用的链接: