How to make the button to disappear by pressing? I suppose that this is somehow connected with the listener, but I don’t know how to specifically delete the button (or make it invisible?).

import java.awt.*; import javax.swing.*; class GraphTest { public static void main(String[] args) { JFrame frame = new JFrame(" Hello!"); //JFrame frame.setSize(new Dimension(400, 300)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); Container container = frame.getContentPane(); //Container container.setLayout(new BorderLayout()); JButton button = new JButton("Click me!"); //JButton button.addActionListener(new MyActionListner()); button.setPreferredSize(new Dimension(100, 50)); JPanel panel = new JPanel(); //JPanel panel.setBackground(Color.darkGray); panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); //GBC gbc.gridx = 0; gbc.gridy = GridBagConstraints.RELATIVE; panel.add(button, gbc); container.add(panel, BorderLayout.CENTER); frame.setVisible(true); } } import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MyActionListner implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println(1); //Вот здесь должна отключаться кнопка } } 

    1 answer 1

    To dynamically remove a component from the Swing panel, you need to define a listener as follows:

     JButton button = new JButton("Click me!"); button.setPreferredSize(new Dimension(100, 50)); button.addActionListener(e -> { System.out.println("remove button"); SwingUtilities.invokeLater(() -> { panel.remove(button); panel.updateUI(); }); }); 
    • This, as I understand it, works in later versions? Version 1.7.0_79 gives an exception, saying that Lambda expressions are not supported at this level of the language. - garbart
    • @dtcobra I only use lambdas for short, no one forbids the use of anonymous classes. - Artem Konovalov