GridLayout抛出非法组件位置

时间:2015-08-26 13:00:50

标签: java swing layout-manager grid-layout

默认情况下,GridLayout(5,3)会以这种方式添加组件:

A B C
D E F
G H I
J K L
M N O 

将组件放置在以下位置:

A F K
B G L
C H M
D I N
E J O

我有这段代码:

//imports...

public class GridLayoutProblem {

    private static final int NUM_ROWS = 5, NUM_COLMS=3;
    private JPanel mainPanel = new JPanel();
    private JPanel buttonPannel = new JPanel(new GridLayout(NUM_ROWS, NUM_COLMS));

    private JButton btnA = new JButton("A");
    private JButton btnB = new JButton("B");
    //same with C, D...
    private JButton btnO = new JButton("O");

    private JComponent[] buttons = {
            btnA, btnB, btnC, btnD, btnE,
            btnF, btnG, btnH, btnI, btnJ,
            btnK, btnL, btnM, btnN, btnO
    };

    public GridLayoutProblem(){
        int i=0;
        for (JComponent button : buttons){
            int index = i%NUM_ROWS*NUM_COLMS+i/NUM_ROWS;
            buttonPannel.add(button,index);
            i++;
        }
        mainPanel.add(buttonPannel);
    }
    //...

但结果是: 线程中的异常" AWT-EventQueue-0" java.lang.IllegalArgumentException:非法组件位置。

1 个答案:

答案 0 :(得分:2)

我做了一个快速测试,似乎你不能跳过索引并将元素添加到更高的索引。

所以你的选择是做这样的事情,

    for (int i = 0; i < NUM_ROWS*NUM_COLMS; i++){
        int index = i%NUM_COLMS*NUM_ROWS+i/NUM_COLMS; // Note the change in calculation. Just interchange rows and colms from your algo.
        buttonPannel.add(button[index],i);
    }