简体   繁体   中英

Add Jbutton to Jpanel

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

This code does not compile because JPanel does not have an overload of add() which takes an array of JButton s, 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 JButton s 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM