如何回到Java中的JFrames

我在JFrame中有一个按钮,如果按下它,它会将我们带到另一个框架。 我用过这段代码:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { SecondForm secondform = new SecondForm(); secondform.setVisible(true); setVisible(false); dispose(); } 

所以新框架打开,一切正常。 然后我在第二帧中放置了另一个按钮 – 以便返回到前一帧。 我用过这段代码:

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { MainForm Mform = new MainForm(); Mform.setVisible(true); setVisible(false); dispose(); } 

问题是,我不认为这是正确的方法。 我想要的是:

  • 隐藏第一帧
  • 展示新的第二个
  • 处理第二个
  • 再次显示第一个

有没有办法使用第一个MainForm实例,而不是每次我想要返回时创建一个新实例。 我监视我的程序,每次来回移动框架,正如我所怀疑的那样,它使用的ram不断增加。

提前致谢。

编辑:我有一个登录系统,当用户输入正确的凭据时,会创建一个新的ManiForm实例。

 MainForm Mform = new MainForm(); Mform.setVisible(true); 

那是我想要使用的实例。 有没有办法让第二种forms的MForm再次可见?

首先感谢您的帮助!

我同意不使用多个JFrame更容易,但是请您告诉我哪个更好的方式来做我在第一篇post中提出的问题? 罗宾给我的答案非常好,但我不知道该把什么作为一个论点*:

 java.awt.EventQueue.invokeLater(new Runnable() { public void run() { * new SecondForm().setVisible(true); } }); 

它来自NetBeans的自动生成代码。

我试过了

 new SecondForm(super).setVisible(true); 

但我仍然遇到编译错误。 显然我必须把super.something()但我不知道是什么。 我试过很多但没有运气。

你不应该使用超过一帧。

除了defaultExitOperation,size,preferedsize和visible true之外,你应该在JFrame中有NOTHING。 而是将所有按钮和字段放入JPanel,并从JFrame添加/删除JPanel。

如果你想打开另一个Window,请使用JDialog。

顺便说一句:你可以让你的MainFrame setVisible为false并打开一个JDialog,你的MainFrame作为父级。 只有当有人写下正确的用户+密码时,才能使主框架可见。

如果将MainForm传递给SecondForm类(例如使用构造函数参数),则SecondForm实例可以使原始MainForm实例再次可见,而不是创建新实例。

例如

 public class SecondForm extends JFrame{ private final MainForm mainForm; public SecondForm( MainForm form ){ mainForm = form; } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { mainForm.setVisible(true); setVisible(false); dispose(); } } 

并在您的MainForm类中

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { SecondForm secondform = new SecondForm( this ); secondform.setVisible(true); setVisible(false); dispose(); } 

对于挥杆应用,标准是使用静态主框架,换句话说,使主框架(mframe)静态并添加弹出新框架,对话框,optionPanes等的方法。您甚至可以控制主框架抛出静态调用。 这就是为应用程序实现UNIQUE FRAME的方式,即使您实例化其他导航框架,所有子框架都可以引用主框架而无需将其作为参数传递给构造函数或创建它的新实例。

主类

`/ *启动应用程序* /

 public class Main{ public static MainFrame MFRAME; public static void main(String[] args){ /*use this for thread safe*/ SwingUtilities.invokeLater(new Runnable() { public void run() { Main.MFRAME = new MainFrame(/*init parms to constructor*/); } }); } } 

`

主框架

`/ *创建主框架* /

 public class MainFrame extends JFrame{ public MainFrame(/*your constructor parms*/){ /* constructor implementation */ } public void openOtherFrame(/*your parms*/){ OtherFrame oFrm = new OtherFrame(/*your parms*/); } /* other methods implementation */ } 

`

儿童框架

`/ *打开控制主框架可见性的子框架* /

 public class OtherFrame extends JFrame{ public OtherFrame(/*your constructor parms*/){ /* hide main frame and show this one*/ Main.MFRAME.setVisible(false); this.setVilible(true); /* do something else */ /* show main frame and dispose this one*/ Main.MFRAME.setVisible(true); this.dispose(); } /* other methods implementation */ } 

`