JOptionPane and reading integers - Beginner Java

夙愿已清 提交于 2019-11-28 02:20:06

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

parseInt Java API

Java Regex Tutorial

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

JOptionPane allows you to supply Object as the message. If this message is a String it will rendered as is, however, if it is a Component of some kind, it will be simply added to the dialog. This makes JOptionPane a very powerful little 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");
                    }
                }
            }
        });
    }
}

Updated

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

But you could also use JSpinners

Or JComboBox

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!