For example, there are 3 classes: MainClass (launches the application), MainFrame (here the main frame) and Buttons (here, respectively, the buttons).

 
public class MainClass { public static void main(String[] args) { SwingUtilities.invokeLater( new Runnable(){ public void run(){ new MainFrame(); } }); } }
 public class MainFrame extends JFrame { private Buttons b1, b2; private JPanel panel; public MainFrame() { setSize(300,300); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); panel = new JPanel(); b1 = new Buttons("b1"); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ panel.remove(b1); repaint(); b2 = new Buttons("b2"); panel.add(b2); } }); panel.add(b1); getContentPane().add(panel); } } 

 public class Buttons extends JButton{ public Buttons(String s) { //super(s); setText(s); setVisible(true); setPreferredSize(new Dimension(150,75)); } } 


Question: when you click on the button, it is deleted, but the second button does not immediately appear, but if you minimize the window and then restore, the second button appears, how to deal with it? =)

    1 answer 1

    It's simple.

     public void actionPerformed(ActionEvent e){ panel.remove(b1); b2 = new Buttons("b2"); panel.add(b2); revalidate(); repaint(); } }); 
    • Yes)) As they say: all ingenious is simple!)) Thank you! - Kobayashi_Maru