JOptionPane 和读取整数 - 初学者 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14783836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:23:32  来源:igfitidea点击:

JOptionPane and reading integers - Beginner Java

javaswingjoptionpane

提问by ShiftyMcGrifty

I currently have code that reads the month, date, and year a user enters in one line (separated by spaces). Here is the code.

我目前有读取用户在一行中输入的月份、日期和年份的代码(用空格分隔)。这是代码。

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

This works fine, the second part is to display a message, if month * day == year, then it is a magical number, if not, then it is not a magical number. It has to be displayed in a dialog box. here is my code for that, and it is working just fine.

这很好用,第二部分是显示一条消息,如果月 * 日 == 年,那么它是一个神奇的数字,如果不是,那么它不是一个神奇的数字。它必须显示在对话框中。这是我的代码,它运行良好。

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

My question is!! How can I get a dialog box to take the inputs of the month, date, and year in one line the way it works in the console. I'm working in DrJava, and the chapter of the book I'm in doesn't help me with this specific use. Any help would be great. Thanks all!

我的问题是!!如何获得一个对话框以在一行中输入月份、日期和年份的输入,就像它在控制台中的工作方式一样。我在 DrJava 中工作,我所在的这本书的章节对我的这种特定用途没有帮助。任何帮助都会很棒。谢谢大家!

回答by MadProgrammer

There are a number of ways to approach the problem depending on ultimately what it is you want to achieve.

有多种方法可以解决问题,具体取决于您最终要实现的目标。

JOptionPaneallows you to supply Objectas the message. If this message is a Stringit will rendered as is, however, if it is a Componentof some kind, it will be simply added to the dialog. This makes JOptionPanea very powerful little API.

JOptionPane允许您Object作为消息提供。如果此消息是 aString它将按原样呈现,但是,如果它是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");
                    }
                }
            }
        });
    }
}

Updated

更新

If I was going to use something like this, I would also use a DocumentFilterto ensure that the user could only enter valid values (examples here)

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

But you could also use JSpinners

但你也可以使用 JSpinners

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

Or JComboBox

或者 JComboBox

enter image description here

在此处输入图片说明

Depending on what it is you want to achieve...

取决于你想要达到的目标......

回答by Smit

You can make use of following to take user input

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

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

拆分 Java API

parseInt Java API

parseInt Java API

Java Regex Tutorial

Java正则表达式教程

回答by Aaron

Here's some code, everything is described in the comments:

这是一些代码,所有内容都在注释中描述:

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

It has an elegant way of notifying you if something went wrong, and everything you need is packaged up in a convenient object.

如果出现问题,它有一种优雅的方式通知您,您需要的一切都打包在一个方便的对象中。