JOptionPane和读取整数 - 初学者Java

时间:2013-02-09 01:10:03

标签: 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();

这个工作正常,第二部分是显示一条消息,如果是月*天==年,那么它是一个神奇的数字,如果没有,那么它不是一个神奇的数字。它必须显示在对话框中。这是我的代码,它工作得很好。

  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);
  }

我的问题是!!如何获得一个对话框,以在控制台中的工作方式将一个月,日期和年份的输入作为一行。我在DrJava工作,我所在的那一章对这个具体用法没有帮助。任何帮助都会很棒。谢谢大家!

3 个答案:

答案 0 :(得分:6)

有很多方法可以解决问题,具体取决于你想要实现的目标。

JOptionPane允许您提供Object作为消息。如果此消息是String,它将按原样呈现,但是,如果它是某种Component,它将被简单地添加到对话框中。这使得JOptionPane成为一个非常强大的小API。

enter image description here

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");
                    }
                }
            }
        });
    }
}

<强>更新

如果我打算使用这样的东西,我还会使用DocumentFilter来确保用户只能输入有效值(示例here

但您也可以使用JSpinners

enter image description here enter image description here

JComboBox

enter image description here

取决于你想要实现的目标......

答案 1 :(得分:2)

您可以使用以下内容来获取用户输入

String word = JOptionPane.showInputDialog("Enter 3 int values");
String[] vals = word.split("\\s+"); // split the sting by whitespaces accepts regex. 
// vals[0] cast to int
// convert string representation of number into actual int value
int day = Integer.parseInt(vals[0]); // throws NumberFormatException
// vals[1] cast to int
// vals[2] cast to int

split Java API

parseInt Java API

Java Regex Tutorial

答案 2 :(得分:2)

以下是一些代码,评论中描述了所有内容:

// import statements
import javax.swing.JOptionPane;
// main class
public class Main {
    // main method
    public static void main(String[] args) {
        // get info
        try {
            Info info = new Info();
        } catch(Exception e) {
            System.err.println("Error! " + e.getMessage());
        }
        // do whatever with the info
    }
    // info class
    static class Info {
        // instance variables
        public int day, month, year;
        // constructor
        public Info() throws Exception {
            // get inputs
            String[] inputs = JOptionPane.showInputDialog(null, 
                "Enter day, month, year").split(" ");
            // not the right size
            if(inputs.length != 3) {   
                throw new Exception("Not enough infomation was given!");
            }
            // get values
            day = Integer.parseInt(inputs[0]);
            month = Integer.parseInt(inputs[1]);
            year = Integer.parseInt(inputs[2]);
        }
    }
}

如果出现问题,它会以优雅的方式通知您,您需要的所有内容都打包在方便的对象中。