Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将JTextfield字符串解析为整数_Java_Swing_Numbers_Jtextfield - Fatal编程技术网

Java 将JTextfield字符串解析为整数

Java 将JTextfield字符串解析为整数,java,swing,numbers,jtextfield,Java,Swing,Numbers,Jtextfield,因此,我需要将String从JTextField转换为int。它在线程“main”java.lang.NumberFormatException中表示异常:对于输入字符串:“”。请帮忙 JTextField amountfld = new JTextField(15); gbc.gridx = 1; // Probably not affecting anything gbc.gridy = 3; // add(amountfld, gbc); String amountString

因此,我需要将
String
JTextField
转换为
int
。它在线程“main”java.lang.NumberFormatException中表示
异常:对于输入字符串:“
”。请帮忙

 JTextField amountfld = new JTextField(15);
 gbc.gridx = 1; // Probably not affecting anything
 gbc.gridy = 3; //
 add(amountfld, gbc);
 String amountString = amountfld.getText();
 int amount = Integer.parseInt(amountString);

您最大的问题是,在创建字段后立即解析文本字段内容,这毫无意义。在允许用户有机会输入数据(最好是在某种类型的监听器中,通常是ActionListener)之后解析数据不是更有意义吗

因此,我的建议有两个方面

  • 不要试图在JTextField创建时立即提取数据,而是在适当的侦听器中提取数据。该类型只能为您所知,但我们通常使用ActionListeners进行此类操作,以便在用户按下JButton时进行解析
  • 在try/catch块中执行解析,在该块中捕获
    NumberFormatException
    。如果发生异常,则通过调用
    setText()
    ,清除jtext字段,然后警告用户他们正在输入无效数据,通常是通过JOptionPane完成的
  • 好的,第三个建议:如果可能的话,尝试通过1)给用户一个默认值,2)甚至不允许用户输入无效数据,使您的GUI完全防白痴。JSlicer、JSpinner或JComobox可以很好地解决这个问题,因为它们会限制允许的输入
  • 例如:

    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class GetNumericData extends JPanel {
        private JTextField amountfld = new JTextField(15);
        private JSpinner amountSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 40, 1));
        private JButton submitButton = new JButton(new SubmitAction("Submit"));
        private JButton exitButton = new JButton(new ExitAction("Exit", KeyEvent.VK_X));
    
        public GetNumericData() {
            add(new JLabel("Amount 1:"));
            add(amountfld);
            add(new JLabel("Amount 2:  $"));
            add(amountSpinner);
            add(submitButton);
            add(exitButton);
        }
    
        // do all your parsing within a listener such as this ActionListener
        private class SubmitAction extends AbstractAction {
            public SubmitAction(String name) {
                super(name);
                int mnemonic = (int) name.charAt(0);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                String amountTxt = amountfld.getText().trim();
                try {
                    int amount1 = Integer.parseInt(amountTxt);
                    // if this parse fails we go immediately to the catch block
    
                    int amount2 = (Integer) amountSpinner.getValue();
                    String message = String.format("Your two amounts are %d and %d", amount1, amount2);
                    String title = "Amounts";
                    int messageType = JOptionPane.INFORMATION_MESSAGE;
                    JOptionPane.showMessageDialog(GetNumericData.this, message, title, messageType);
    
                } catch (NumberFormatException e1) {
                    String message = "You can only enter numeric data within the amount field";
                    String title = "Invalid Data Entered";
                    int messageType = JOptionPane.ERROR_MESSAGE;
                    JOptionPane.showMessageDialog(GetNumericData.this, message, title, messageType);
                    amountfld.setText("");
                }
            }
        }
    
        private class ExitAction extends AbstractAction {
    
            public ExitAction(String name, int mnemonic) {
                super(name);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        }
    
        private static void createAndShowGui() {
            JFrame frame = new JFrame("Get Data");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new GetNumericData());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    您最大的问题是,在创建字段后立即解析文本字段内容,这毫无意义。在允许用户有机会输入数据(最好是在某种类型的监听器中,通常是ActionListener)之后解析数据不是更有意义吗

    因此,我的建议有两个方面

  • 不要试图在JTextField创建时立即提取数据,而是在适当的侦听器中提取数据。该类型只能为您所知,但我们通常使用ActionListeners进行此类操作,以便在用户按下JButton时进行解析
  • 在try/catch块中执行解析,在该块中捕获
    NumberFormatException
    。如果发生异常,则通过调用
    setText()
    ,清除jtext字段,然后警告用户他们正在输入无效数据,通常是通过JOptionPane完成的
  • 好的,第三个建议:如果可能的话,尝试通过1)给用户一个默认值,2)甚至不允许用户输入无效数据,使您的GUI完全防白痴。JSlicer、JSpinner或JComobox可以很好地解决这个问题,因为它们会限制允许的输入
  • 例如:

    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class GetNumericData extends JPanel {
        private JTextField amountfld = new JTextField(15);
        private JSpinner amountSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 40, 1));
        private JButton submitButton = new JButton(new SubmitAction("Submit"));
        private JButton exitButton = new JButton(new ExitAction("Exit", KeyEvent.VK_X));
    
        public GetNumericData() {
            add(new JLabel("Amount 1:"));
            add(amountfld);
            add(new JLabel("Amount 2:  $"));
            add(amountSpinner);
            add(submitButton);
            add(exitButton);
        }
    
        // do all your parsing within a listener such as this ActionListener
        private class SubmitAction extends AbstractAction {
            public SubmitAction(String name) {
                super(name);
                int mnemonic = (int) name.charAt(0);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                String amountTxt = amountfld.getText().trim();
                try {
                    int amount1 = Integer.parseInt(amountTxt);
                    // if this parse fails we go immediately to the catch block
    
                    int amount2 = (Integer) amountSpinner.getValue();
                    String message = String.format("Your two amounts are %d and %d", amount1, amount2);
                    String title = "Amounts";
                    int messageType = JOptionPane.INFORMATION_MESSAGE;
                    JOptionPane.showMessageDialog(GetNumericData.this, message, title, messageType);
    
                } catch (NumberFormatException e1) {
                    String message = "You can only enter numeric data within the amount field";
                    String title = "Invalid Data Entered";
                    int messageType = JOptionPane.ERROR_MESSAGE;
                    JOptionPane.showMessageDialog(GetNumericData.this, message, title, messageType);
                    amountfld.setText("");
                }
            }
        }
    
        private class ExitAction extends AbstractAction {
    
            public ExitAction(String name, int mnemonic) {
                super(name);
                putValue(MNEMONIC_KEY, mnemonic);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        }
    
        private static void createAndShowGui() {
            JFrame frame = new JFrame("Get Data");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new GetNumericData());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    
    发件人:

    抛出:NumberFormatException-如果字符串不包含 可分解整数

    空字符串
    不是可解析的整数,因此如果未输入值,代码将始终生成
    NumberFormatException

    有很多方法可以避免这种情况。您只需检查从
    amountField.getText()
    获得的
    字符串值是否已填充。您可以创建一个自定义的
    IntegerField
    ,它只允许整数作为输入,但可以添加到
    JTextField
    。创建仅允许整数输入的文档:

    public static class IntegerDocument extends PlainDocument {
    
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            StringBuilder sb = new StringBuilder(str.length());
            for (char c:str.toCharArray()) {
                if (!Character.isDigit(c)) {
                    sb.append(c);
                }
            }
            super.insertString(offs, sb.toString(), a);
        }
    }
    
    现在,使用方便的
    getInt
    方法创建一个
    IntergerField
    ,如果未输入任何内容,该方法将返回零:

    public static class IntegerField extends JTextField {
        public IntegerField(String txt) {
            super(txt);
            setDocument(new IntegerDocument());
        }
    
        public int getInt() {
            return this.getText().equals("") ? 0 : Integer.parseInt(this.getText());        
        }
    }
    
    现在,您可以从
    amountField
    中检索整数值,而无需进行任何检查:

    JTextField amountField = new IntegerField("15");
    ...
    //amount will be zero if nothing is entered
    int amount = amountField.getInt();
    
    发件人:

    抛出:NumberFormatException-如果字符串不包含 可分解整数

    空字符串
    不是可解析的整数,因此如果未输入值,代码将始终生成
    NumberFormatException

    有很多方法可以避免这种情况。您只需检查从
    amountField.getText()
    获得的
    字符串值是否已填充。您可以创建一个自定义的
    IntegerField
    ,它只允许整数作为输入,但可以添加到
    JTextField
    。创建仅允许整数输入的文档:

    public static class IntegerDocument extends PlainDocument {
    
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            StringBuilder sb = new StringBuilder(str.length());
            for (char c:str.toCharArray()) {
                if (!Character.isDigit(c)) {
                    sb.append(c);
                }
            }
            super.insertString(offs, sb.toString(), a);
        }
    }
    
    现在,使用方便的
    getInt
    方法创建一个
    IntergerField
    ,如果未输入任何内容,该方法将返回零:

    public static class IntegerField extends JTextField {
        public IntegerField(String txt) {
            super(txt);
            setDocument(new IntegerDocument());
        }
    
        public int getInt() {
            return this.getText().equals("") ? 0 : Integer.parseInt(this.getText());        
        }
    }
    
    现在,您可以从
    amountField
    中检索整数值,而无需进行任何检查:

    JTextField amountField = new IntegerField("15");
    ...
    //amount will be zero if nothing is entered
    int amount = amountField.getInt();
    

    将JFormattedTextField与数字格式化程序一起使用,在Oracle教程中有更多内容,JSpinner对可能的方法也是正确的,还有JTextField和DocumentFilter的组合,所有的树形方法在这里都有很多次关于将JFormattedTextField与数字格式化程序一起使用,在Oracle教程中有更多内容,JSpinner对可能的方法也是正确的,还有JTextField和DocumentFilter的组合,所有的树方式在这里都有很多次是关于非常感谢你much@AshfordTulgaa没问题,更新了我的答案clarity@AshfordTulgaa没问题,为了清楚起见,更新了我的答案