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