简体   繁体   English

在JFrame中调用JPanel

[英]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. 我认为这是一件简单的事情,但是我在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. 我有一个像菜单一样扩展JPanel的类,用户没有单击开始按钮并调用另一个扩展JPanel的类,但是它不起作用。 I call the first class in my main method that is a simple JFrame, the code is bellow: 我在主方法中调用的第一个类是简单的JFrame,代码如下:

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: 在InitialScreen中,我有一个带有以下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. 使用this运算符时要小心。 If you follow my example, you won't be able to use this . 如果您遵循我的示例,则将无法使用this You will need to either use the ActionEvent object to get the source object, or you will need to reference some global variable; 您将需要使用ActionEvent对象来获取源对象,或者需要引用一些全局变量。 for example tela in your case. 例如您的情况下的tela

Also, I don't think is a good idea to make InitialScreen an anonymous object. 另外,我认为将InitialScreen设为匿名对象也不是一个好主意。 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. 按钮应该在面板内部声明,并且我显示的逻辑应该在InitialScreen面板类中。 In the frame, the only thing you will need to do is create an instance of InitialScreen and add it to your frame. 在框架中,您唯一需要做的就是创建一个InitialScreen实例并将其添加到框架中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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