Java 容器删除方法无法正常工作

2024-05-01

我添加了 1.TextArea 2.TextField 然后我开始在容器上连续添加 JButton...,现在通过使用 JRadioButton 我想使用此代码从容器中删除 JButton

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 应该被删除,因为 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();
        }
    }

}

The Container由返回getContentPane()默认情况下,是contentPane of a JRootPane由管理顶层容器 http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html, JFrame。尽管“为了方便起见,add方法及其变体,remove and setLayout已被覆盖转发到contentPane如有必要,“没有a priori了解框架内部使用组件索引的方法。

相反,您自己添加JComponent到框架并对其进行操作;JPanel是一个共同的选择。

附录:还可以考虑替代布局,例如CardLayout,如图所示here https://stackoverflow.com/a/5655843/230513.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 容器删除方法无法正常工作 的相关文章

随机推荐