Shi*_*fty 1 java swing joptionpane
我目前有代码,用于读取用户在一行中输入的月份,日期和年份(以空格分隔).这是代码.
Scanner input = new Scanner(System.in);
int day = 0;
int month = 0;
int year = 0;
System.out.printf("enter the month, date, and year(a 2 numbered year). Put a space between the month, day, and year");
month = input.nextInt();
day = input.nextInt();
year = input.nextInt();
Run Code Online (Sandbox Code Playgroud)
这个工作正常,第二部分是显示一条消息,如果是月*天==年,那么它是一个神奇的数字,如果没有,那么它不是一个神奇的数字.它必须显示在对话框中.这是我的代码,它工作得很好.
if((day * month) == year)
{
String message = String.format("%s", "The date you entered is MAGIC!");//If the day * month equals the year, then it is a magic number
JOptionPane.showMessageDialog(null, message);
}
if((day * month) != year)
{
String message = String.format("%s", "The date you entered is NOT MAGIC!");//If the day * month does not equal the year, it is not a magic number
JOptionPane.showMessageDialog(null, message);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是!! 如何获得一个对话框,以在控制台中的工作方式将一个月,日期和年份的输入作为一行.我在DrJava工作,我所在的那一章对这个具体用法没有帮助.任何帮助都会很棒.谢谢大家!
有很多方法可以解决问题,具体取决于您希望实现的目标.
JOptionPane允许您提供Object消息.如果此消息是a String,它将按原样呈现,但是,如果它是Component某种类型,它将被简单地添加到对话框中.这是JOptionPane一个非常强大的小API.

public class TestOptionPane07 {
public static void main(String[] args) {
new TestOptionPane07();
}
public TestOptionPane07() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField fldDay = new JTextField(3);
JTextField fldMonth = new JTextField(3);
JTextField fldYear = new JTextField(4);
JPanel message = new JPanel();
message.add(fldDay);
message.add(new JLabel("/"));
message.add(fldMonth);
message.add(new JLabel("/"));
message.add(fldYear);
int result = JOptionPane.showConfirmDialog(null, message, "Enter Date", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
String sDay = fldDay.getText();
String sMonth = fldMonth.getText();
String sYear = fldYear.getText();
JOptionPane.showMessageDialog(null, "You enetered " + sDay + "/" + sMonth + "/" + sYear);
try {
int day = Integer.parseInt(sDay);
int month = Integer.parseInt(sMonth);
int year = Integer.parseInt(sYear);
JOptionPane.showMessageDialog(null, "You enetered " + day + "/" + month + "/" + year);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "The values you entered are invalid");
}
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
更新
如果我打算使用这样的东西,我还会使用DocumentFilter来确保用户只能输入有效值(这里的示例)
但你也可以使用 JSpinners


要么 JComboBox

取决于你想要实现的目标......
| 归档时间: |
|
| 查看次数: |
11508 次 |
| 最近记录: |