Java 单击按钮打开新面板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2979679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open new panel with button clicked
提问by bat
Java Swing GUI:
Java Swing GUI:
I am using ActionListener to preform the action when a button is clicked. 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.
我正在使用 ActionListener 在单击按钮时执行操作。我想要做的是当一个按钮被点击时,打开一个新面板,但从不同的文件加载/获取新面板。
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. Since netbeans only displays the main panel.
我问这个的原因是因为当我用 netbeans 创建一个 GUI 程序时......我不知道如何在按钮被点击时使用“设计视图”制作一个新平面。由于 netbeans 只显示主面板。
回答by Robert
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);
}
回答by exodrifter
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.
通常,在同一个地方编写类代码更容易。不要忘记您可能必须从类中删除组件。