Java 打开新 JFrame 时如何禁用主 JFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3029079/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:45:24  来源:igfitidea点击:

How to disable main JFrame when open new JFrame

javaswingjframe

提问by user236501

Example now I have a main frame contains jtable display all the customer information, and there was a create button to open up a new JFrame that allow user to create new customer. I don't want the user can open more than one create frame. Any swing component or API can do that? or how can disabled the main frame? Something like JDialog.

示例现在我有一个包含 jtable 显示所有客户信息的主框架,并且有一个创建按钮来打开一个新的 JFrame 允许用户创建新客户。我不希望用户可以打开多个创建框架。任何摆动组件或 API 都可以做到这一点?或者如何禁用主框架?类似 JDialog 的东西。

采纳答案by akf

I would suggest that you make your new customer dialog a modal JDialogso that you do not allow input from other dialogs/frames in your app while it is visible. Take a look at the modality tutorialfor details.

我建议您将新客户对话框设为模态,JDialog以便在应用程序中的其他对话框/框架可见时不允许输入。有关详细信息,请查看模态教程

回答by Hyman

just use firstFrame.setVisible(false)on the first frame. This will make it hidden..

firstFrame.setVisible(false)在第一帧上使用。这将使它隐藏..

if you want a more general approach you could have a reference to the current displayed frame somewhere and change it when a new frame requests to be shown

如果你想要一个更通用的方法,你可以在某处引用当前显示的帧,并在新帧请求显示时更改它

JFrame currentFrame;

void showRequest(JFrame frame)
{
  currentFrame.setVisible(false);
  currentFrame = frame;
  currentFrame.setVisible(true);
}

回答by Hatem

I think you should use this code for the main jframe when you trying to open new one :

我认为当您尝试打开新的 jframe 时,您应该将此代码用于主 jframe:

this.setEnabled(false);

this.setEnabled(false);

回答by J---

Sorry for the late answer but have you considered the Singleton design pattern? It will return the same instance of a class whenever you want the class. So if the user wants a frame to enter the details, there will only be one frame open (same instance)

抱歉回答晚了,但您是否考虑过单例设计模式?只要您需要该类,它就会返回一个类的相同实例。所以如果用户想要一个框架输入详细信息,只会打开一个框架(同一个实例)

It goes something like this:

它是这样的:

private static MySingleFrame instance = null; //global var

private MySingleFrame() { } //private constructor 
private static MySingleFrame getInstance()
{

if(instance == null)
{
instance = new MySingleFrame();
}

//returns the same instance everytime MySingleFrame.getInstance() is called
return instance; 


}

回答by Wasif Faisal

You can use:

您可以使用:

 private void btn_NewFormActionPerformed(java.awt.event.ActionEvent evt) { 

             this.hide();
             new Frm_NewFormUI().setVisible(true);

 }