简体   繁体   English

单击按钮打开新面板

[英]Open new panel with button clicked

Java Swing GUI: Java Swing GUI:

I am using ActionListener to preform the action when a button is clicked. 我使用ActionListener来执行单击按钮时的操作。 What i want to do is when a button is clicked, open a new panel, but load/get the new panel from a different file. 我想要做的是单击按钮时,打开一个新面板,但是从其他文件加载/获取新面板。

This is what i have so far but i rather just link to another file. 这是我到目前为止的内容,但我只是链接到另一个文件。 THANKS! 谢谢! =] =]

   public void actionPerformed(java.awt.event.ActionEvent e) {
                    //something like this...
                    loadFile(newPlane.java);
}

Update: 更新:

        inventoryDisplay.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            inventoryDisplayActionPerformed(evt);
        }


        private void inventoryDisplayActionPerformed(java.awt.event.ActionEvent evt) {
        //open a new panel by opening a new file ex: inventory.java  
        }

the reason im asking this is because when im creating a GUI program with netbeans... i have no idea how to make a new planel with the "design view" when the button is clinked. 我问这个的原因是因为当我用netbeans创建一个GUI程序时...我不知道如何在链接按钮时用“设计视图”制作一个新的planel。 Since netbeans only displays the main panel. 由于netbeans仅显示主面板。

Java does not work on the basis of includes, so you need to define classes, and instantiate them. Java不能在包含的基础上工作,因此您需要定义类并实例化它们。

you could make a static factory method to get a fully configured JPanel: 您可以使用静态工厂方法来获取完全配置的JPanel:

public class ClassWhereStored {
    public static JPanel newJPanel(){
        JPanel panel = new JPanel();
        // configure it
        return panel;
    }
}

... ...

public void actionPerformed(java.awt.event.ActionEvent e) {
    JPanel panel = ClassWhereStored.newPanel()
    frame.add(panel);          
}

What you'll need to do, for you code, is to put the class file in the same folder. 对于您的代码,您需要做的是将类文件放在同一文件夹中。

ie, in relation to the following code... 即,关于以下代码...

public void actionPerformed(java.awt.event.ActionEvent e) {
    //something like this...
    loadFile(newPlane.java);
}

...you need to compile newPlane.java, take the class file that is created and place it in the same folder as your class that's trying to "loadfile". ...您需要编译newPlane.java,获取已创建的类文件,并将其放置在与尝试“加载文件”的类相同的文件夹中。

Then, in your class (I'm assuming it extends JFrame or JPanel), you need to do this, instead of loadFile: 然后,在您的类中(我假设它扩展了JFrame或JPanel),您需要这样做,而不是loadFile:

public void actionPerformed(java.awt.event.ActionEvent e) {
    newPlane plane = new newPlane();
    add(plane);
}

Usually, it's just easier to write the class code in the same place. 通常,在同一个地方编写类代码会更容易。 Don't forget that you might have to remove components from your class. 不要忘记,您可能必须从类中删除组件。

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

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