I think it's because the button gets removed while there are still methods on it that are not finished, such as fireActionPerformed. So it makes sense. But I have looked it up and using removeAll is mentioned a lot of places and seems to cause no problems like mine. So even though removeAll removed everything, including the root pane, it should still work if I am to believe several other forum posts regarding updating a JFrame.
So hopefully someone can shed some light on this. Yes, I COULD just add the button to a JPanel and then just remove that, but given that this should work, I'm interested in solving this problem or figuring out why it doesn't work when others have had no problems with using that method, and not in working around it.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class TestFrame extends JFrame {
public TestFrame() {
JButton ok = new JButton("OK");
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
replace();
}
});
add(ok);
pack();
setVisible(true);
}
public void replace() {
this.removeAll();
add(new JTextField("Hey"));
}
public static void main(String[] args) {
new TestFrame();
}
}


Sign In
Create Account


Back to top









