在 Java 中显示弹出消息窗口?

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

Display pop-up message window in Java?

javaswingjoptionpanejdialog

提问by Howcan

I read about JDialogs and JOptionPane messages but I still can't get it to work. I have a GUI class that extends JFrame. All I want to do is have a popup at the beginning of my program which informs the user about a couple of things. In my main I create the following gui:

我阅读了 JDialogs 和 JOptionPane 消息,但我仍然无法让它工作。我有一个扩展 JFrame 的 GUI 类。我想要做的就是在我的程序开始时弹出一个窗口,通知用户一些事情。在我的主要我创建以下gui:

GUI g = new GUI();

Right after that I was to display the window. I have tried the following in the main method:

在那之后,我要显示窗口。我在主要方法中尝试了以下内容:

JOptionPane.showMessageDialog(g, "work?");
JOptionPane.showMessageDialog(frame, "work?"); //(frame was used in documentation example so I tried it)

I also tried to add the pop up into the GUI class with the following

我还尝试使用以下内容将弹出窗口添加到 GUI 类中

JOptionPane.showMessageDialog(this, "work?"); //(I'm not exactly sure what the Frame Owner parameter is supposed to be, unless I'm confusing this with JDialog.)

In any case, how would I make this window appear? Every single one of the methods I tried compiled, and nothing happened.

无论如何,我将如何使这个窗口出现?我尝试编译的每一种方法都没有发生。

public class GUI extends JFrame implements ActionListener{
     private Container background;
     private static buttons etc...
     private static JLabel disp,edisp;
     private static JTextArea info;
     //setting up the GUI for my program, adding action listeners, I can post more if    necessary
}

And then I have the main where I want to call the pop up window

然后我有我想调用弹出窗口的主要内容

public static void main(String[] args){
    GUI g = new GUI();
    JOptionPane.showMessageDialog(g,"Work?");
}

回答by Otanan

Make sure that these are called near the beginning, be it in the main method or not. Also, try just setting the first parameter as null. So it reads:

确保这些在开头附近被调用,无论是否在 main 方法中。另外,尝试将第一个参数设置为 null。所以它写道:

JOptionPane.showMessageDialog(null,"Work?");

Also, remember to import it!

还有,记得导入哦!