简体   繁体   中英

Call JPanel inside JFrame

I imagine that it's a simple thing to do, but i did not find something that help me in google.

I have a class that extends JPanel like a menu, the users than click in a start button and calls another class extending JPanel, but it does not work. I call the first class in my main method that is a simple JFrame, the code is bellow:

JFrame tela = new JFrame("teste");
    tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tela.setSize(800,600);
    tela.add(new InitialScreen());

    tela.setVisible(true);

And in InitialScreen i have a button with the following actionEvent:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    this.add(new BackgroundGame());
    this.validate();
    this.revalidate();
    this.setVisible(true);
}

but with this I press the button and nothing occurs.

Can someone help me?

Thanks.

You will need to incorporate something like this in your code:

    JButton button1 = new JButton("Button 1");
    InitialScreen panel = new InitialScreen(); // I am assuming this is a JPanel
    button1.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            // TODO add your logic
        }
    });
    panel.add(button);
    tela.add(panel);

Be careful using the this operator. If you follow my example, you won't be able to use this . You will need to either use the ActionEvent object to get the source object, or you will need to reference some global variable; for example tela in your case.

Also, I don't think is a good idea to make InitialScreen an anonymous object. You should create an explicit instance like I did above.

The button SHOULD be declared inside the panel and the logic I showed should be in the InitialScreen panel class. In the frame, the only thing you will need to do is create an instance of InitialScreen and add it to your frame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM