tags:

views:

32

answers:

3

What i need some help with is removing a label and creating a new one with a button click. At the moment this will add a new label but won't remove the old. I can't find a command that will work, northpanel.remove() will destroy the panel and the previous label, but then i can't create any new ones.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class test2 extends JFrame implements ActionListener {

 private JTextField textfield;

 private JPanel northPanel = new JPanel();
 private JPanel southPanel = new JPanel();

 public test2() {
  setSize(400, 200);

  BorderLayout layout = new BorderLayout ();
  setLayout(layout);

  JLabel label1 = new JLabel("remove this");
  northPanel.add(label1);

  JLabel label2 = new JLabel("Enter move");
  southPanel.add(label2);
  textfield = new JTextField(10);
  southPanel.add(textfield);
  JButton button = new JButton("Move / remove label");
  button.addActionListener(this);
  southPanel.add(button);

  add(northPanel, BorderLayout.NORTH);
  add(southPanel, BorderLayout.SOUTH);
 }

 @Override
 public void actionPerformed(ActionEvent e) {
  String text = textfield.getText();

  if (text.equals("")) {
   System.out.println("textfield is empty");
  } else {
   System.out.println(text);
  }


 // northPanel.remove();

  JLabel label3 = new JLabel("new label");
  northPanel.add(label3);

  repaint();
  validate();
 }

 public static void main(String[] args) {
  test2 app = new test2();
  app.setVisible(true);
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}
+1  A: 

Why don't you change the text of the label, instead of removing the old and adding a new one?

private JPanel northPanel = new JPanel();
private JPanel southPanel = new JPanel();
private JLabel label1 = new JLabel("remove this");

// ....


@Override
 public void actionPerformed(ActionEvent e) {
  // ...

  label1.setText("new text");

  // ...
 }
Cristian
i tried that before and it didn't work but now it did, i guess i wasn't updating the gui before...silly me.
ric
@ric, so are you going to accept the answer so people know the problem is solved?
camickr
A: 

Why are you attempting to remove and add a label. All you need to do is:

label1.setText("some different text");

However, the general rule for removing / adding components to a visible GUI is to do:

panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
camickr
A: 

Declare label1 as an instant variable. Then initialise the label1 in the constructor. Now change the actionPerformed as below

 public void actionPerformed(ActionEvent e) {
  String text = textfield.getText();

  if (text.equals("")) {
   System.out.println("textfield is empty");
  } else {
   System.out.println(text);
   label1.setText(text);
  }
Lalith