as you can tell I am fairly new to Swing and ran into a small issue when building. Basically I want the user to be able to click on a button and a text field will appear. The issue is when I do setVisible(false) first and then try to setVisible(true) with a button action it does not appear. But if I reverse the conditions and set true first, the text field disappears when the button is clicked. It is very strange to me but hopefully someone can help. Thanks!
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLayout(new FlowLayout());
JTextField field = new JTextField();
field.setPreferredSize(new Dimension(100, 20));
// adding and setting visibility to false
frame.add(field);
field.setVisible(false);
JButton button = new JButton();
button.setPreferredSize(new Dimension(100, 20));
// Pointer to textfield where textfield SHOULD becoming visible once clicked
button.addActionListener(e -> field.setVisible(true));
frame.add(button);
frame.setVisible(true);
}
I've tried changing when the field is being added, and when the visibility is being set to false.
You nee to add frame.validate()
to your listener.
It will force layout to realign components.
button.addActionListener(e -> {
field.setVisible(!field.isVisible());
frame.validate();
});