动态添加后删除JTextFields

时间:2014-03-12 10:30:26

标签: java swing jlabel jtextfield

我的目标是通过单击JLabel同时删除两个JTextField。

我已经创建了这样的文本字段:

public void mouseClicked(MouseEvent e) {


            inc++;
            txtName= new JTextField();
            txtNumber = new JTextField();
            txtName.setName("txtName"+inc);
            txtNumber.setName("txtNumber" + inc);

            pnlPanel.add(txtName);
            pnlPanel.add(txtNumber);

            if(count>0){
                x+=50;
                y+=50;

                txtName.setBounds(225,6+y, 182, 27);
                txtNumber.setBounds(35, 6+y, 182, 27);
                txtName.setName(tempBox+count);
                if(pnlTxtText.getComponentCount() >9){

                    pnlPanel.setPreferredSize(new Dimension(450+y,50+y));
                    pnlPanel.add(txtStudName);
                    pnlPanel.add(txtStudentNumber);

                    frmFrame.repaint();
                    scrpPanel.revalidate();
                }
            }
            frmFrame.repaint();
        }

    });

这是我删除文本字段的代码:

public void mouseClicked(MouseEvent e) {
    int countPlace= pnlPanel.getComponentCount();
    int countOfRemaining =countPlace;
    pnlPanel.remove(--countOfRemaining);
    frmFrame.revalidate();
    pnlPanel.remove(--countOfRemaining);
    frmFrame.revalidate();
}

});

不是删除同一行上的txtfields,而是逐个删除它,我不想这样做。请帮我。谢谢。

To further understand my problem i posted a picture. Ever time I click a label, it should delete the last two fields but instead of doing that, it deletes txtfield from a different place

3 个答案:

答案 0 :(得分:2)

pnlPanel.revalidate()

之前致电repaint()

并且不要使用setBounds()。相反,定义porper LayoutManager

答案 1 :(得分:1)

而不是这个,

public void mouseClicked(MouseEvent e) {
        int countPlace= pnlPanel.getComponentCount();
        int countOfRemaining =countPlace;
        pnlPanel.remove(countOfRemaining-1);
        frmFrame.repaint();
        pnlPanel.remove(countOfRemaining-1);
        frmFrame.repaint();
    }
});

使用此

public void mouseClicked(MouseEvent e) {
        int countPlace= pnlPanel.getComponentCount();
        int countOfRemaining =countPlace;
        pnlPanel.remove(--countOfRemaining);
        frmFrame.revalidate();
        pnlPanel.remove(--countOfRemaining);
        frmFrame.revalidate();
    }
});

上面的抛出了一个ArrayIndeOutOfBounds异常,因为删除组件后,计数剩余变量没有减少。因此,当您尝试第二次删除时,索引会超出范围。

答案 2 :(得分:0)

我建议您以JPanels的形式将所有<Integer, JPanel>添加到地图(我使用HashMap)。按顺序将它们全部命名,然后只需Map.remove(Map.size() - 1)Map.remove(Map.size() - 2)

您还可以通过执行Map.keySet()来获取当前的整数(键);

Map<Integer, JPanel> temp = new HashMap<Integer, JPanel>();
temp.put(0, new JPanel());
temp.put(1, new JPanel());
temp.put(2, new JPanel());
temp.remove(temp.size() - 1);

使维护多组面板变得更加容易。在我的应用程序中,我不是用数字控制它们,而是使用短名称。