Search code examples
javaswingjapplet

How to add new Panel in the same Applet using ActionListener


I have an applet which has a Panel. In the Panel a button is added which on clicking will remove the current Panel and a new Panel will be added to the current Applet.

But I am not getting the desired output !!!

I want to replace the Display Panel currently added to the Applet by a new Panel from a ActionListener.

Kindly tell the mistake !!

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JPanel;

public class Init extends JApplet {

    public Display ref;
    public NewDisplay ref2;

    public class Display extends JPanel  implements ActionListener {

        public Display() {
            initComponents();
        }

        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            jButton1.setText("New Game");
            add(jButton1);
            jButton1.addActionListener(this);

        }
        public javax.swing.JButton jButton1;

        @Override
        public void actionPerformed(ActionEvent e) {
            String x = e.getActionCommand();
            if (x.equals("New Game")) {
                System.out.println("clicked");
                //ref.setVisible(false);
                this.removeAll();
                //add(ref2);
                add(ref2);
                invalidate();
                revalidate();
                repaint();
            }
        }
    }

    public class NewDisplay extends JPanel {

        public NewDisplay() {
            setSize(800, 600);
        }

        @Override
        public void paintComponent(Graphics g) {
            g.setColor(Color.RED);
            g.fillRect(0, 0, 800, 600);
        }
    }

    @Override
    public void init() {
        ref = new Display();
        ref2 = new NewDisplay();
        add(ref);
        setSize(800,600);

    }
}

Solution

  • You should NOT be using the setSize() method to set the size of a component.

    Layout managers use the preferred size of the component. You should be overriding the getPreferredSzie() method of your panel to returnthe desired size.

    public class NewDisplay extends JPanel {
    
        public NewDisplay() {
        //   setSize(800, 600);
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return new Dimension(800, 600);
        }
    
        @Override
        public void paintComponent(Graphics g) {
            g.setColor(Color.RED);
            g.fillRect(0, 0, 800, 600);
        }
    }
    

    Or a better solution is to use a Card Layout and just sway the panels in and out. See How to Use Card Layout.