0

i made a calculator with 2 text fields number 1 and number 2 and 4 buttons for operations + , - , x , / and a text field for the result i want to let the input in text fields for number 1 and 2 be numeric only and when i put letter message appear in result field Invalid Input thanks in advance for help it will be better if the solution with regular expression and i want to save the whole operation to be able to load again i already made jbuttons for SAVE , LOAD

This is my code any modifications?

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

}}
Hitesh
  • 3,449
  • 8
  • 39
  • 57
  • you should post a more simple example of what you are trying to do. It is too much code to comb through as is. – feltersnach Sep 19 '15 at 04:26
  • i dont know where is the specific part that make the problem + i have two problems Numeric Input and Save Input and result to be able to load it again sry for long code but i think i should post it all – Eslam Niazy Sep 19 '15 at 04:29
  • 1
    http://stackoverflow.com/questions/6111003/its-possible-in-swing-configure-a-jtextfield-to-only-accept-numbers/6111095#6111095 this will answer your question. – feltersnach Sep 19 '15 at 04:31
  • 2
    You want a JFormattedTextField. https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html – wolfcastle Sep 19 '15 at 04:36

2 Answers2

0

Using DocumentFilter and regex you can check what type of input you need. For getting number this can help you.

((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);
            }
        }
    });
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42
-1

Use key listner interface and handle events I am writing a sample code to allow only numbers in JTextField, here I am showing only keyReleased(KeyEvent e) implementation you will also need to implement keyTyped and keyPressed just implement it blank to compile the code. In my code range from 48 to 57 is acsii value of 0 to 9 and 127 is delete key, 8 is backspace and 65535 is arrows key codes. ask doubt if any. Show msg box if letter is entered in textfield hope you implement it.

             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);
Piyush Yawalkar
  • 252
  • 1
  • 4
  • 17