Add Jbutton to Jpanel

后端 未结 1 1836
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 10:53

can somebody tell me what is wrong with this code i am trying to add the buttons to my JPanel

ArrayList buttons = new ArrayList();
         


        
相关标签:
1条回答
  • 2021-01-27 11:24

    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;
    }
    
    0 讨论(0)
提交回复
热议问题