danrodi
danrodi

Reputation: 296

Removing a label in Java

I have this piece of code, which should remove a label, when a button is pressed:

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);
    }
});

But when I click on the button, it doesn't remove the label text. Only when I resize the window (for example set it to full screen), the label text dissapears.

Upvotes: 0

Views: 11198

Answers (2)

ryvantage
ryvantage

Reputation: 13486

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.

Upvotes: 1

Katana24
Katana24

Reputation: 8959

From this previous answer located here, put forth by camickr, you need to do the following:

The code would be (assuming the use of a JPanel):

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

You need to remove the component and then tell the panel to layout the remaining components.

Upvotes: 6

Related Questions