Add Jbutton to Jpanel

可紊 提交于 2021-02-05 11:10:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!