1

So I have a JTextField displayed in a GUI. What I want to do is remove the text field when someone presses enter. I have already added ActionListener. I just want to know how to automatically update it without having to minimize it or something.

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

public class Window extends JFrame{
private JTextField TextField0;
private JTextField TextField1;
private JCheckBox CheckBox0;

//CONSTRUCTOR
public Window(){
    super("Checkbox");
    setLayout(new FlowLayout());

    TextField0 = new JTextField("Add field",15);
    add(TextField0);
    CheckBox0 = new JCheckBox("");



    HandlerClass handler = new HandlerClass();
    TextField0.addActionListener(handler);
}
    //Method: HandlerClass
public class HandlerClass implements ActionListener{
    public void actionPerformed(ActionEvent event){
        if(event.getSource()==TextField0){
            CheckBox0.setText(String.format("%s",event.getActionCommand()));
        }
    }
}
}

EDIT: I figured it out guys! :D Thanks!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
alexdr3437
  • 61
  • 2
  • 8

4 Answers4

3

Have a look at using CardLayout.The CardLayout class manages two or more components (usually JPanel instances) that share the same display space.

Add textField0 and checkBox0 to 2 separate JPanels. In the ActionListener call

checkBox0.setText(textField0.getText());

Use CardLayout#next to flip from the first to the second panel.

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
3

Assuming it lives in a container, such as a JPanel, use the remove() method, and ask for the panel to repaint:

panel.remove(textField);
panel.revalidate();
panel.repaint();
ashatch
  • 310
  • 1
  • 10
0

You must revalidate() and repaint() the container.

SSC
  • 2,956
  • 3
  • 27
  • 43
0

Change the declaration of the JTextField to public / private depending on how you access it:

public JTextField jtf = new JTextField();

And when you create your window:

jtf = new JTextField();
jtf.addActionListener {
removeJTF();

Use this code to remove the JTextField:

public void removeJTF() {

    exampleFrame.remove(jtf);
}
Aaron
  • 992
  • 3
  • 15
  • 33