0

我有这段代码,labelbutton按下 a 时,它应该删除 a :

final JLabel label = new JLabel("Label text");
rightPanel.add(label);

final JButton remove = new JButton("Remove label");
leftPanel.add(remove);
add.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)
    {
        rightPanel.remove(label);
    }
});

但是当我点击 时button,它不会删除标签文本。只有当我调整窗口大小(例如将其设置为全屏)时,标签文本才会消失。

4

2 回答 2

6

根据camickr提出的这个先前的答案,您需要执行以下操作:

代码将是(假设使用 JPanel):

panel.remove(...);
panel.revalidate();
panel.repaint(); // sometimes needed

您需要删除组件,然后告诉面板布局剩余的组件。

于 2013-11-08T15:16:37.213 回答
1

Perhaps not an answer to your question but what I consider helpful advice: only add/remove components when it is absolutely necessary. If you get creative, you'll find that there are often better solutions than adding/removing components. For example, instead of removing a JButton, consider disabling it instead.

In your situation, you could always just do label.setText(""). This way you don't need to revalidate() and repaint().

I very rarely call revalidate() and repaint() in my code. I think it's better to update the existing components than to remove/add them.

于 2013-11-09T16:55:04.873 回答