问题
can somebody tell me what is wrong with this code i am trying to add the buttons to my JPanel
ArrayList<JButton> buttons = new ArrayList<JButton>();
JPanel createButtonspane(){
bpanel = new JPanel();
for(int i=0; i<10; i++){
buttons.add(new JButton(""+i));
bpanel.add(buttons);
}
return bpanel;
}
回答1:
This code does not compile because JPanel does not have an overload of add() which takes an array of JButtons, so you can not add a whole array of buttons to the JPanel (even if it was possible, you would need to do it outside of your for()-loop).
Simply add your button directly to the JPanel:
JPanel createButtonspane(){
bpanel = new JPanel();
for(int i=0; i<10; i++){
bpanel.add(new JButton(""+i));
}
return bpanel;
}
If you still need to refer to the individual JButtons later, add them to the array in addition:
JPanel createButtonspane(){
bpanel = new JPanel();
for(int i=0; i<10; i++){
JButton button = new JButton(""+i);
buttons.add(button);
bpanel.add(button);
}
return bpanel;
}
来源:https://stackoverflow.com/questions/16475596/add-jbutton-to-jpanel