2012-08-01 44 views
2

我HAVA添加1.TextArea 2.TextField 后来我开始添加的JButton先后对集装箱...,现在通过使用一个JRadioButton我想使用此代码的Java容器取出方法无法正常工作

i=0; 
k=0; 
while(!birdButton[i].isSelected()){ 
    i++;  
} 
System.out.println(i); 
k=i+2; 
list.removeElementAt(i); 
listName.removeElementAt(i); 
System.out.println(k); 
c.getContentPane().remove(k); 
从容器中取出的JButton

但是当我选择第一个单选按钮时,应该删除第一个JButton,因为k = i + 2; 而不是删除这一个它删除TextArea(第一个)。 当我选择第三个单选按钮时,第一JButton被删除。任何人都可以让我知道问题是什么?也System.out.println(i);System.out.println(k);没有打印任何价值....这里是代码

public class RadioDemo implements ActionListener { 

    String buttonName; 
    JPanel radioPanel = new JPanel(); 
    ButtonGroup group = new ButtonGroup(); 
    Enumeration enl; 
    int result; 
    ActionEvent e; 
    JRadioButton birdButton[]; 
    int i, k; 

    Vector<String> listName; 
    Vector<JComponent> list; 
    Container c; 

    public RadioDemo(Vector<String> listName,Vector<JComponent> list,Container c) { 

     birdButton=new JRadioButton[listName.size()]; 
     this.listName=listName; 
     this.c=c; 
     this.list=list; 

     i = 0; 
     for (String buttonName : listName){ 
       birdButton[i] = new JRadioButton(buttonName); 
       birdButton[i].setActionCommand(buttonName); 
       group.add(birdButton[i]); 
       birdButton[i].addActionListener(this); 
       radioPanel.add(birdButton[i]); 
       i++; 
     } 

     birdButton[0].setSelected(true); 
     radioPanel.setLayout(new BoxLayout 

     (radioPanel,BoxLayout.Y_AXIS)); 
            //birdButton.setBorder 

     (BorderFactory.createEmptyBorder(5,5,5,5)); 
     result = JOptionPane.showConfirmDialog(null, radioPanel, "Please choose", JOptionPane.OK_CANCEL_OPTION);     
     show(); 
    } 

    /** Listens to the radio buttons. */ 
    public void actionPerformed(ActionEvent e) { 
     this.e = e; 
    } 

    public void show() { 
     if (result == JOptionPane.OK_OPTION) { 
      i = 0; 
      k = 0; 
      while (!birdButton[i].isSelected()) { 
       i++; 

      } 
      System.out.println(i); 
      k = i + 2; 
      list.removeElementAt(i); 
      listName.removeElementAt(i); 
      System.out.println(k); 
      c.getContentPane().remove(k); 
      c.getContentPane().validate(); 

      // System.out.println(e.getActionCommand()); 
      // c.getContentPane().rePaint(); 
     } 
    } 

} 
+0

怎么样,而是你保持你想要删除,也许有点像'HashMap'按钮单选按钮之间的关系的船? – MadProgrammer 2012-08-01 22:52:33

+0

我需要看看你是如何构建UI的 – MadProgrammer 2012-08-01 22:53:31

回答

6

Container通过getContentPane()返回时,默认情况下,一个JRootPanecontentPanetop-level containerJFrame管理。尽管“为方便起见,add方法及其变体,removesetLayout已被覆盖以根据需要转发至contentPane,但”并不知道有关组件索引的内部使用的框架“。

image

相反,你自己JComponent添加到框架并在其上进行操作; JPanel是常见的选择。

附录:也考虑替代布局如CardLayout所示here

+0

@kleopatra:绝对正确;感谢您的评论;更上面。 – trashgod 2012-08-02 08:58:04

+0

只是阅读:-)很酷的编辑,很想给你第二个upvote! – kleopatra 2012-08-02 09:06:19