Search code examples
javaswingjpaneljbuttonactionlistener

JPanel How to make button work?


As you read this code, you will realize I got one action event to work, it opens up a new JPanel that displays the button that will run the ballBounce, but for now im stuck trying to get a working button within that frame because that frame is already within a actionEvent, any help?

 public class MainJPanelOperation
    {
        public static void main(String[] a)
        {

            JPanel panel1 = new JPanel(new GridLayout(5, 10, 1, 1));
            JButton t1 = new JButton();
            JButton t2 = new JButton();
            JButton letsStart = new JButton("Start The Program!");
            JButton t3 = new JButton();
            JButton t4 = new JButton();
            //letsStart.setBounds(200,250,12,12);
            panel1.add(t1);
            panel1.add(t2);
            panel1.add(letsStart);
            panel1.add(t3);
            panel1.add(t4);
            final JFrame frame1 = new JFrame("Game");
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame1.add(panel1);
            frame1.setSize(1000,1000);
            frame1.setVisible(true);
            t1.setVisible(false);
            t2.setVisible(false);
            t3.setVisible(false);
            t4.setVisible(false);
            letsStart.setBackground(Color.yellow);
            panel1.setBackground(Color.black);
            letsStart.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println("panel 2 main menu intro online");
                    JPanel panelMM = new JPanel(new GridLayout(5, 10, 1, 0));
                    JButton MM1 = new JButton("BallBounce");
                    panelMM.add(MM1);
                    JFrame frameMM = new JFrame("Game/Main Menu");
                    frameMM.add(panelMM);
                    frameMM.setSize(1000,1000);
                    frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frameMM.setVisible(true);
                    frame1.setVisible(false);
                }
            });//end of start sequence

        }
    }

Solution

  • JPanel panelMM = new JPanel(new GridLayout(5, 10, 1, 0));    
    JButton MM1 = new JButton("BallBounce");
    panelMM.add(MM1);
    final JFrame frameMM = new JFrame("Game/Main Menu");
    frameMM.add(panelMM);
    frameMM.setSize(1000,1000);
    frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    letsStart.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println("panel 2 main menu intro 
                    frameMM.setVisible(true);
                    frame1.setVisible(false);
                }
            });
    

    You can make frameMM final and there is no need to have all of your code inside the ActionListener.