我有以下代码:
public static void main(String[] args) throws MalformedURLException {
// ask player for his username, this is used for login.
Random rand = new Random();
int r = rand.nextInt(1000 - 1) + 1;
Object[] options1 = {"Login", "Random Username",
"Quit"};
JPanel panel = new JPanel();
panel.add(new JLabel("Enter your desired username:"));
JTextField textField = new JTextField(16);
panel.add(textField);
//random usernames
String words = "username:noob:player:slayer:foreveruser:forevernoob:foreverplayer:lol:wrectlikeaboos:darkalien:gold_in_silver:zeebra:zebra:maddox:canada:canadian:richtard";
String[] wordsAsArray = words.split(":");
int index = new Random().nextInt(wordsAsArray.length);
String randomWord = wordsAsArray[index];
Random num = new Random();
int numr = num.nextInt(1000 - 1) + 1;
int result = JOptionPane.showOptionDialog(null, panel, "Forever: Login",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options1, null);
if (result == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Logged in as " + textField.getText());
}
//randomusername = no
//quit = cancel
if (result == JOptionPane.CANCEL_OPTION) {
System.exit(1)
}
if (result == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "Logged in as " + randomWord + numr);
}
//String user = JOptionPane.showInputDialog("Enter your username: ", "User"+r);
Login client = new Login("hi");
}
public Login(String userName) throws MalformedURLException {
Launcher launcher = new Launcher();
launcher.init();
this.username = userName;
}
基本上,当您运行该程序时,会弹出一个对话框,询问您的用户名。如果按quit,它将以没有任何用户名的方式运行游戏(不应该发生),如果按X,它也将运行。我将如何使它仅结束程序而不是在没有任何用户名的情况下运行。
谢谢。
最佳答案
在您处理按quit的操作的地方,您可以致电System.exit(int)
(假设您没有要清理或保存的内容,而shutdown hook中没有这样做)。