1

Just how you add JLabels, JTextFields, JButtons by doing this add(label1); add(button1);

how to remove?

I have a button that will remove a particular JTextField.

The button:

thehandler3 handler3 = new thehandler3();
button3.addActionListener(handler3); // first x button

private class thehandler3 implements ActionListener{
    public void actionPerformed(ActionEvent event){

        remove(field1);

    }}

It is not working. I get no compliation or execution error.

razshan
  • 1,128
  • 12
  • 41
  • 59

2 Answers2

4

You need to call remove() on the container you want to remove the component from, like this:

panel.remove(label1);

You will also want to consider threading issues when updating the UI:

Event Dispathcing Thread

Isaac Truett
  • 8,734
  • 1
  • 29
  • 48
  • I tried doing remove(field1); (its a JTextField)..does not seems to work. with panel.remove(field1) i get an error. – razshan Mar 01 '11 at 02:07
4

The code would be:

panel.remove(...);
panel.revalidate();
panel.repaint(); // sometimes needed

You need to remove the component and then tell the panel to layout the remaining components.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I don't have panels. My class extends JFrame. Usually instead of doing panel.add(button1);... i am doing add(button1) and it works well for me. – razshan Mar 01 '11 at 02:09
  • 1
    @razshan, you should NOT be extending a JFrame. You are not changing the behaviour of the frame. A better way to create a GUI is to use a panel to hold your components and then add the panel to the frame. Add the panel directly to the frame or set the content pane of your frame to be the custom panel. I suggest you read the Swing tutorial on "Using Top Level Container" (http://download.oracle.com/javase/tutorial/uiswing/components/toplevel.html) to understand this. You can also download and run the examples to see simple code on a better way to create your GUI so you don't extend JFrame. – camickr Mar 01 '11 at 02:19
  • @camickr. I have incorporated panel to hold my components. However, I have bunch of actionListeners. and In them, the program can't recognize 'frame' or 'panel'. – razshan Mar 01 '11 at 02:31