嗯,你创建这个类的方式让我想知道你的项目中是否还有另一个类实际上是 startup 类,因为,为了显示名称输入的输入框,您需要创建一个 First 实例(不是 JOptionPane()),以便构造函数可以触发它。
如果这是您项目中唯一的类,那么您仍然可以触发输入框,但您需要在 main() 方法中创建 First 的实例,如下所示:
public static void main(String[] args) {
/* You could just use: new First(); but you'll see
the NetBeans yellow Warning underline beneath the
code line which you can ignore. Better to provide
a variable to the instance of First as done here. */
First f2 = new First();
}
总体而言,将名称输入提示直接放在 main() 方法中可能会更好。一旦提供了名称,您还希望将该名称保留在一个字符串变量中,该变量可能对整个类都是全局的,而不仅仅是在构造函数的范围内。 String i1 或许应该声明为类成员变量,并命名为更合适的名称,例如:String userName;。
我得到了 JFrame 的想法,因为如果没有父组件并且使用了 null,JOptionPanes 喜欢隐藏在 IDE(或其他“在顶部”窗口)后面。但是,如果您这样做,则对其进行设置,使其不会无意中使用默认的EXIT_ON_CLOSE 属性值关闭您的应用程序。你会希望它是DISPOSE_ON_CLOSE。您还希望将 JFrame 的 setAlwaysOnTop 属性设置为布尔值 true。使用 JOptionPane 后,请务必处理 JFrame,否则您的应用程序将保持活动状态,直到某些东西实际关闭它。您可以在下面的示例中看到这一点:
import javax.swing.*;
public class First {
private static JFrame dialogPARENT; // Parent used for dialogs that don't have a parent.
private static String userName; // Holds the User Name supplied in either the Input Box or Setter method.
// Class Constructor
First() {
dialogPARENT = new JFrame();
dialogPARENT.setAlwaysOnTop(true);
dialogPARENT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialogPARENT.setLocationRelativeTo(null);
userName = JOptionPane.showInputDialog(dialogPARENT, "Enter Your Name:");
dialogPARENT.dispose(); // dispose of the JFrame.
}
public static void main(String[] args) {
First first = new First(); // Fires the constructor
// Display the User Name. As you can see, basic HTML can
// be used in your Message Box dialog display string.
JOptionPane.showMessageDialog(dialogPARENT, "<html>The name you entered is:<br><br>"
+ "<center><font color=red><b>" + userName + "</b></font></center><br></html>",
"Supplied User Name", JOptionPane.INFORMATION_MESSAGE);
dialogPARENT.dispose(); // dispose of the JFrame.
}
}