如何在Textfield中输入数字

时间:2015-09-19 04:23:56

标签: java swing save jtextfield

我制作了一个计算器,其中包含2个文本字段编号1和编号2和4个按钮,用于操作+, - ,x,/和结果的文本字段我想让输入在1和2的文本字段中只有数字和当我把信件消息出现在结果字段无效输入感谢提前帮助它会更好,如果解决方案与正则表达式,我想保存整个操作,以便能够再次加载我已经为SAVE制作了jbuttons, LOAD

这是我的代码是否有任何修改?

import java.awt.BorderLayout;

public class MainWindow extends JFrame {

private JPanel contentPane;
private JTextField txtNumber1;
private JTextField txtAnswer;
private JTextField txtNumber2;
private JButton sub;
private JButton mul;
private JButton div;
private JButton add;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    String LookAndFeel = UIManager.getSystemLookAndFeelClassName();
    try {
        UIManager.setLookAndFeel(LookAndFeel);
    } catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (InstantiationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (UnsupportedLookAndFeelException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainWindow frame = new MainWindow();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public MainWindow() {
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 430, 263);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblNumber1 = new JLabel("Number 1:");
    lblNumber1.setBounds(21, 44, 80, 14);
    contentPane.add(lblNumber1);

    txtNumber1 = new JTextField();
    txtNumber1.setBounds(102, 38, 100, 26);
    contentPane.add(txtNumber1);
    txtNumber1.setColumns(10);

    JLabel lAnswer = new JLabel("Answer :");
    lAnswer.setBounds(21, 181, 80, 14);
    contentPane.add(lAnswer);

    txtAnswer = new JTextField();
    txtAnswer.setBounds(102, 175, 100, 26);
    contentPane.add(txtAnswer);
    txtAnswer.setColumns(10);

    JButton btnSave = new JButton("Save");
    btnSave.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser fc = new JFileChooser();
            fc.showSaveDialog(MainWindow.this);
            File f =  fc.getSelectedFile();
        }
            void saveToFile(String fileName, JTextField textField) throws Exception {
                   FileOutputStream out = new FileOutputStream(fileName, true);
                   out.write(textField.getText().getBytes());
                } 

    });
    btnSave.setBounds(315, 31, 89, 47);
    contentPane.add(btnSave);

    JButton btnLoad = new JButton("Load");
    btnLoad.setBounds(315, 168, 89, 47);
    contentPane.add(btnLoad);

    JButton btnReset = new JButton("Reset");
    btnReset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){
            txtNumber1.setText(null);
            txtNumber2.setText(null);
            txtAnswer.setText(null);
        }
        });
    btnReset.setBounds(315, 98, 89, 47);
    contentPane.add(btnReset);

    txtNumber2 = new JTextField();
    txtNumber2.setBounds(102, 75, 100, 26);
    contentPane.add(txtNumber2);
    txtNumber2.setColumns(10);

    JLabel lblNumber2 = new JLabel("Number 2:");
    lblNumber2.setBounds(21, 81, 80, 14);
    contentPane.add(lblNumber2);

    add = new JButton("+");
    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            String n1 = txtNumber1.getText();
            String n2 = txtNumber2.getText();
            Float num1 = Float.parseFloat(n1);
            Float num2 = Float.parseFloat(n2);   
            Object clicked = a.getSource();
            if(add==clicked)
                txtAnswer.setText(String.valueOf(num1+num2));

            }
        }
    );
    add.setBounds(50, 110, 89, 23);
    contentPane.add(add);

    sub = new JButton("-");
    sub.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent s) {
            String n1 = txtNumber1.getText();
            String n2 = txtNumber2.getText();
            Float num1 = Float.parseFloat(n1);
            Float num2 = Float.parseFloat(n2);   
            Object clicked = s.getSource();
            if(sub == clicked)
            {
            txtAnswer.setText(String.valueOf(num1-num2));
            }
        }
    });
    sub.setBounds(153, 110, 89, 23);
    contentPane.add(sub);

    mul = new JButton("x");
    mul.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent m) {
            String n1 = txtNumber1.getText();
            String n2 = txtNumber2.getText();
            Float num1 = Float.parseFloat(n1);
            Float num2 = Float.parseFloat(n2);   
            Object clicked = m.getSource();
            if(mul == clicked)
            {
            txtAnswer.setText(String.valueOf(num1*num2));
            }
        }
    });
    mul.setBounds(50, 144, 89, 23);
    contentPane.add(mul);

    div = new JButton("/");
    div.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent d) {
            String n1 = txtNumber1.getText();
            String n2 = txtNumber2.getText();
            Float num1 = Float.parseFloat(n1);
            Float num2 = Float.parseFloat(n2);   
            @SuppressWarnings("unused")
            Object clicked = d.getSource();
            if(num2 == 0)
                txtAnswer.setText("Can't Divide By Zero");
                else
                txtAnswer.setText(String.valueOf(num1/num2));
                }

    });
    div.setBounds(153, 141, 89, 23);
    contentPane.add(div);           

}}

2 个答案:

答案 0 :(得分:0)

使用DocumentFilterregex,您可以查看所需的输入类型。为了获得数字,这可以帮助你。

((AbstractDocument)txtNumber1.getDocument()).setDocumentFilter(new DocumentFilter() {
        @Override
        public void replace(FilterBypass fb, int offset, int length,
                String text, AttributeSet attrs)
                throws BadLocationException {
            String numS = fb.getDocument().getText(0,
                    fb.getDocument().getLength());
            numS += text;
            if (numS.matches("^[0-9]+[.]?[0-9]*$")) {
                super.replace(fb, offset, length, text, attrs);
            }
        }

        @Override
        public void insertString(FilterBypass fb, int offset,
                String string, AttributeSet attr)
                throws BadLocationException {
            String numS = fb.getDocument().getText(0,
                    fb.getDocument().getLength());
            numS += string;


            if ( numS.matches("^[0-9]+[.]?[0-9]*$")) {
                super.insertString(fb, offset, string, attr);
            }
        }
    });

答案 1 :(得分:-1)

使用键列表器接口和处理事件我正在编写示例代码以仅允许JTextField中的数字,这里我只显示keyReleased(KeyEvent e)实现,您还需要实现keyTyped和keyPressed,只需将其实现为空白即可编译码。在我的代码范围从48到57是acsii值0到9和127是删除键,8是退格键,65535是箭头键代码。如果有的话,请怀疑。如果在textfield中输入字母,则显示msg框,希望您实现它。

             KeyListener keyListener; 
             keyListener = new KeyListener(){
               @Override
        public void keyReleased(KeyEvent e) {

               char code=e.getKeyChar();

            if(((int)code<48 || (int)code>57 )&& (int)code!=8 && (int)code!=127 &&(int)code!=65535)
            {
                String str=text.getText();
                str=str.substring(0, str.length()-1);
                text.setText(str);
                str=text.getText();
                for(int i=0; i<str.length(); i++)
                {
                    if(((int)str.charAt(i)<48 || (int)str.charAt(i)>57) && (int)str.charAt(i)!=8)
                    {
                        String c=""+str.charAt(i);
                        String a=str.replace(c,"");
                        System.out.println("a="+a);
                        text.setText(a);
                    }
                }
            }


        }

    };
    text.addKeyListener(keyListener);