Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPanel removeAll doesn't get rid of previous components

Tags:

java

swing

jpanel

I have a swing application in which I display images in a JPanel. If the app is unable to produce the image I want to remove the previous one from the JPanel and replace it with a JTextField and message. I can add the text field , but it's drawn on top of the previous contents, which is itself a subclass of JPanel. Here's what I have:

private void displayMessage(String message) {
  JTextField tf = new JTextField(message);
  cdPanel.removeAll();
  cdPanel.add(tf, BorderLayout.NORTH);//tried lots of variations, inc. no layout    
  cdPanel.validate();
}

How can I get cdPanel to completely redraw itself?

like image 761
jaybee Avatar asked Aug 01 '13 17:08

jaybee


People also ask

How do I remove a component from a JPanel?

The answer is pretty simple. Use getComponents() to iterate through an array of components added to the JPanel. Find the kind of component you want to remove, using instanceof for example. In my example, I remove any JCheckBoxes added to my JPanel.

Can you pack a JPanel?

Then the answer to your question is no, there is no other way to do this, the API was designed from the start to make use of the layout managers.

Why do we use panels while creating gui applications in java?

It allows you to group components together, it allows you to devise complex interfaces, as each panel can have a different layout, allowing you to leverage the power of different layout managers.

What is JPanel layout?

Layout Managers in Swing The "layout" of a content pane (JPanel), is the arrangement of its components (text, images, buttons, checkboxes, radio buttons, etc.). Luckily, Java provides some pre-designed patterns for arranging the display (order) of components, referred to as Layout Managers.


1 Answers

You can simply try calling :

cdPanel.revalidate();
cdPanel.repaint();   // This is required in some cases

instead of

cdPanel.validate();
like image 187
nIcE cOw Avatar answered Oct 17 '22 06:10

nIcE cOw