0

I am trying to create buttons at random places in frame in x and y axises with different gridwidth and gridheight but the thing is,i am not able to run it cos i am getting errors :/ here is my code.. What am i doing wrong?

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

}
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
the feels
  • 107
  • 7

2 Answers2

2

Size of newConstraints is 9 and when the value of i=9 it will break because there is no value for 9th index.

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

Add some value say {0,0,1,1} to 9th index and you panel will be loaded.

One more thing, First character for class name should be in upper case. Use Calculator as class name instead of calculator.

Atul
  • 1,392
  • 3
  • 17
  • 31
2

You get an error :

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

Because you try to loop throw an array which contain 10 element and in reality your array contain only 9.

You have to change :

newbuttons = new JButton[10];

to

newbuttons = new JButton[9];
YCF_L
  • 49,027
  • 13
  • 75
  • 115