【问题标题】:Java: newConstraints isn't working [duplicate]Java:newConstraints 不起作用[重复]
【发布时间】:2017-07-19 22:02:36
【问题描述】:

我正在尝试在 x 和 y 轴的框架中以不同的网格宽度和网格高度创建按钮,但问题是,我无法运行它,因为我收到错误:/ 这是我的代码.. 什么我做错了吗?

public class calculator extends JPanel{
public static final int WIDTH=320;
public static final int HEIGHT=480;
private GridBagLayout layout;
private GridBagConstraints gbc;
private JButton[] newbuttons;
private JTextField text;
private int[][] newConstraints= new int[][]{
        {0,5,2,1},
        {0,4,1,1},
        {1,4,1,1},
        {2,4,1,1},
        {0,0,1,1},
        {0,0,1,1},
        {0,0,1,1},
        {0,0,1,1},
        {0,0,1,1},
};
public calculator(){
    setPreferredSize(new Dimension(WIDTH,HEIGHT));
    layout=new GridBagLayout();
    layout.columnWidths= new int[]{110,120,40,80};
    layout.rowHeights= new int[]{80,80,80,80,80,80};
    setLayout(layout);
    gbc= new GridBagConstraints();
    newbuttons=new JButton[10];
    for(int i=0;i<newbuttons.length;i++){
        newbuttons[i]=new JButton(""+i);
        gbc.gridx=newConstraints[i][0];
        gbc.gridy=newConstraints[i][1];
        gbc.gridwidth=newConstraints[i][2];
        gbc.gridheight=newConstraints[i][3];
        gbc.fill=GridBagConstraints.BOTH;
        add(newbuttons[i],gbc);
    }


}
    public static void main(String[] args) {
        JFrame frame= new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(new calculator(), BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

}

【问题讨论】:

  • 如果您询问错误,您需要发布完整的错误消息。
  • 您确定错误在此代码中吗? JFrame和main方法在哪里?

标签: java swing layout indexoutofboundsexception


【解决方案1】:

你得到一个错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9

因为您尝试循环抛出一个包含 10 个元素的数组,而实际上您的数组仅包含 9 个。

你必须改变:

newbuttons = new JButton[10];

newbuttons = new JButton[9];

【讨论】:

    【解决方案2】:

    newConstraints 的大小为 9,当 i=9 的值时它会中断,因为第 9 个索引没有值。

    private int[][] newConstraints= new int[][]{
        {0,5,2,1},//0
        {0,4,1,1},//1
        {1,4,1,1},//2
        {2,4,1,1},//3
        {0,0,1,1},//4
        {0,0,1,1},//5
        {0,0,1,1},//6
        {0,0,1,1},//7
        {0,0,1,1},//8
                  //9 
     };
    

    向第 9 个索引添加一些值,例如 {0,0,1,1},您的面板将被加载。

    还有一点,类名的第一个字符应该是大写的。使用Calculator 作为类名而不是calculator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2013-08-11
      • 2015-07-04
      • 2012-10-26
      • 2013-01-17
      • 2018-10-16
      • 2016-09-19
      • 2016-08-11
      相关资源
      最近更新 更多