gpt4 book ai didi

java - GridLayout 抛出非法组件位置

转载 作者:行者123 更新时间:2023-11-30 08:09:43 25 4
gpt4 key购买 nike

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

A B CD E FG H IJ K LM N O 

To have the components disposed in the following positions:

A F KB G LC H MD I NE J O

I have this code:

//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 中的异常:非法组件位置。

最佳答案

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

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

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

关于java - GridLayout 抛出非法组件位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32227371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com