How do I remove multiple labels from a panel?

In reference to this: How do I display something I enter in a JOptionPane on the JFrame?

I've made a JList which also outputs what I've inputted, and it displays on the JPanel as JLabels, as what I've done using the link. However, how do I remove the respective JLabels this time? Thanks so much to anyone who will help!

Edit: What I want to do is when I click the remove button in my JList, the label on the panel will also be removed.


I'll add an answer to provide some code since I have the feeling my comments are misunderstood.

First, if it isn't necessary, don't use a label per list entry but use one label whose contents is a concatenation of the list entries. Then update the label's text whenever the list changes.

Basically, you have a method like this:

private void updateLabel() {
   StringBuilder text = new StringBuilder();
   //this assumes listModel is a DefaultListModel and doesn't contain null values
   //adapt for other list models and add any necessary checks
   for( Object entry : listModel.toArray() ) {
     text.append( entry.toString()).append(" ");
   label.setText( text.toString() );

Then add a listener to your list model:

listModel.addListDataListener( new ListDataListener() {      
  public void intervalAdded(ListDataEvent e) {

  public void intervalRemoved(ListDataEvent e) {

  public void contentsChanged(ListDataEvent e) {

Thus, when you change something in the list the label would be updated automatically.

Do the following:

String stringToRemove = "CATS";
jLabel.setText(jLabel.getText().replace(stringToRemove, "");

If you have say a JLabel set to: "CATS DOGCATS APPLE" it will change to " DOG APPLE" after removing the CATS string

1) put there JPopupMenu rather than JOptionPane

2) add List Selection Listener to JList, set Selection Model

3) check if SelectedIndex > -1, if passed then removeItem(s) from JList or from ListModel

4) better would be add JList Items to the DefaultListModel

Need Your Help

C# : Using this in a constructor

c# constructor

In C# is it ok to use this in the constructor? (i.e., is it ok to reference the instance in the constructor)

Random number in c# which should be exactly random every time?

c# random-sample

i am trying to generate random number for my mental math quiz game. But i think i am doing something wrong.Please help me to correct my code.Please try to include some sort of explanation, why my c...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.