Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Removing a JComponent Dynamically

 
john latham
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now that i can add a component dynamically, i would like to also remove it when needed.

How would i go about this, currently this is what im doing in my actionPerformed method:

if the checkbox is checked add the graph to the panel, if unchecked remove it from the panel. The problem is im making the panel on the fly so i cant use .remove to get rid of it, or can I? Here is my attempt


[ September 07, 2006: Message edited by: john latham ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a lot depends on where this is
LineGraphGui l = new LineGraphGui("Node "+row, "Time", "Temperature");

if it is part of the method that adds, then remove(l) will not be referring to
the previously added (l), but to the new (l) just created.

here's a simple demo using a checkbox to add/remove

 
john latham
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm i see what you mean, but is it possible to add something i create as an anyonous class and remove it? Because i dont want to make a graph unless the user asks for it.

like this:

if(graph) {
lineGraphPanel.add(new LineGraphGui("Node "+row, "Time", "Temperature"));
lineGraphPanel.validate();
}

else {
this.lineGraphPanel.remove(???);
lineGraphPanel.validate();
}
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try this
(but instanceof can have it's own little problems, if not careful)

 
john latham
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It works, thank you very much!! Ive never used instanceof before, its very useful.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic