gpt4 book ai didi

java - 从外部类切换 Java 中的 jPanel

转载 作者:行者123 更新时间:2023-11-30 05:04:09 27 4
gpt4 key购买 nike

我有 jFrameMainForm,其中包含 main()placePanel(panel) 和下拉菜单。从下拉菜单中的项目中,我调用 placePanel(panel) 方法将特定面板放置在 jFrame 容器中。这工作得很好。

但是,当我单击 jPanel 类中的按钮时,我不知道如何切换面板。当我尝试从加载到 jFrame 的任何 jPanel 调用 jFrameMainForm.placePanel(panel) 时的容器,我收到错误:无法引用非静态内容等。我也尝试了Mainform.getContainer().add(panel),但它没有也工作。

我不知道如何从另一个类访问 MainForm 的容器,或者如何使用另一个面板中的方法切换面板。

谢谢

最佳答案

如果你想从另一个对象中调用一个对象的方法,你将需要一个对第一个对象的引用,这样你就可以在 Activity 对象本身上调用该方法,而不是在类上调用该方法(因为你'目前正在尝试做)。解决此问题的一种方法是将保存 JPanel 的类的引用传递给具有按钮的操作监听器代码的类(可能在后者的构造函数中)。换句话说,您需要将对当前 Activity 且可视化的 MainForm 对象的引用传递到具有按钮的 ActionListener 的类中。

顺便问一下,您是否正在将 JPanel 替换为 CardLayout?如果没有,我建议您研究一下,因为这通常是最简单的方法。

编辑:

例如,假设您有一个名为 MainForm 的类,它有一个名为 swapJPanels 的公共(public)方法,允许它交换 View ,而另一个类 MyPanel 拥有您的 JButton,想要从 MainForm 类调用方法,那么您可以给出MyPanel 是一个构造函数,它采用 MainForm 参数并允许您将当前 MainForm 对象(类内部的 this)的引用传递到 MyPanel 对象中:

主窗体:

class MainForm extends JFrame { 

public MainForm() {
MyPanel myPanel = new MyPanel(this); // pass "this" or the current MainForm reference to MyPanel
}

public void swapJPanels(int panelNumber) {

}
}

我的面板:

class MyPanel extends JPanel {
private MainForm myMainForm; // holds the reference to the current MainForm object

public MyPanel(MainForm myMainForm) {
this.myMainForm = myMainForm; // set the reference

JButton swapPanelBtn = new JButton("Swap Panel");
swapPanelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
swapPanelBtnActionPerformed();
}
});
}

private void swapPanelBtnActionPerformed() {
myMainForm.swapJPanels(0); // calling a method on the reference to the current MainForm object
}
}

关于java - 从外部类切换 Java 中的 jPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5693878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com