import javax.swing.*;
public class TestProject {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Just about to draw the best piece of artwork in my life, need input please.");
String name= JOptionPane.showInputDialog("Imagine a car, what is it's name?");
JOptionPane.showMessageDialog(null, "Ah okay, so it's name is " + name);
String bodyColour = JOptionPane.showInputDialog("Cool. What colour was the body of the car? \n Blue, Red, Black, Green or Orange? (More to come in DLC's) ");
JOptionPane.showMessageDialog(null, "Mhmm");
String wheelColour= JOptionPane.showInputDialog("Colour of the wheels? ");
JOptionPane.showMessageDialog(null, "Very ordinary...");
String doorColour = JOptionPane.showInputDialog("Last... And probably least, colour of the door?");
JOptionPane.showMessageDialog(null, "Finished the drawing!");
}
}
这是我上面的代码,我想知道用户如何按下取消,(因为通常它就像用户按下了'#ok;')或弹出提示中的x按钮,我想它可以使用某种类型的监听器或者System.exit(0);但我不知道如何实现它,因为我对Java来说还不够新
答案 0 :(得分:1)
这可以解决您的问题
if(name == null || (name != null && ("".equals(name))))
{
System.exit(0);// or you can throw exception
}
在第一个JOptionPane.showInputDialog()
您的代码(刚刚添加了上面的代码段)
import javax.swing.*;
public class TestProject {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Just about to draw the best piece of artwork in my life, need input please.");
String name= JOptionPane.showInputDialog("Imagine a car, what is it's name?");
if(name == null || (name != null && ("".equals(name))))
{
System.exit(0);// or you can throw exception
}
JOptionPane.showMessageDialog(null, "Ah okay, so it's name is " + name);
String bodyColour = JOptionPane.showInputDialog("Cool. What colour was the body of the car? \n Blue, Red, Black, Green or Orange? (More to come in DLC's) ");
JOptionPane.showMessageDialog(null, "Mhmm");
String wheelColour= JOptionPane.showInputDialog("Colour of the wheels? ");
JOptionPane.showMessageDialog(null, "Very ordinary...");
String doorColour = JOptionPane.showInputDialog("Last... And probably least, colour of the door?");
JOptionPane.showMessageDialog(null, "Finished the drawing!");
}
}
答案 1 :(得分:0)
如果用户按下提示上的取消或x按钮,则showInputDialog
将返回null。
答案 2 :(得分:0)
像这样使用confirmDialog:
int answer = JOptionPane.showConfirmDialog(null, "Your Message", "Your Title", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
if(answer == JOptionPane.CANCEL_OPTION){
System.out.println("canceled");
} else {
System.out.println("OK");
}