alicedimarco
alicedimarco

Reputation: 325

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.

Upvotes: 0

Views: 1206

Answers (4)

Thomas
Thomas

Reputation: 88707

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) {
     updateLabel();
  }

  public void intervalRemoved(ListDataEvent e) {
     updateLabel();
  }

  public void contentsChanged(ListDataEvent e) {
     updateLabel();
  }
});

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

Upvotes: 1

fnst
fnst

Reputation: 5694

I think you're looking for a ListModel. When you implemented it, you can easily add/remove items.

For example:

// adding
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");

list = new JList(listModel);

// removing (the selected item)
int index = list.getSelectedIndex();
listModel.remove(index);

For further information see the Tutorial.

Upvotes: 0

mKorbel
mKorbel

Reputation: 109813

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

Upvotes: 1

GETah
GETah

Reputation: 21419

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

Upvotes: 1

Related Questions