0

I have a code where I can put numbers and a point to make a decimal, but I need JTextField to accept only numbers from 1 to 10 and then use it for a calculation

this is the code to accept only numbers and a dot, i have no idea how to accept numbers from 1 to 10 only

    txtNota1 = new JTextField();
    txtNota1.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            
            char c = e.getKeyChar();
            
            if ((!Character.isDigit(c)) && (c != '.')) {
                e.consume();
            }
        }
    });
    txtNota1.setBounds(124, 38, 143, 20);
    panel.add(txtNota1);
    txtNota1.setColumns(10);

And this is the code to do a calculation, when I use a decimal in txtNote1, like 7.8, it sends me an error and does not do the calculation

    JButton btnCALCULAR = new JButton("CALCULAR");
    btnCALCULAR.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            double n1;
            double n3;
            double prome;
            
            n1 = Integer.parseInt(txtNota1.getText());
            n3 = Integer.parseInt(txtNota3.getText());
            
            prome = (n1+n3)/2;
            
            txtResultado.setText(String.valueOf(prome));
        }
    });
    btnCALCULAR.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnCALCULAR.setBounds(357, 111, 145, 37);
    contentPane.add(btnCALCULAR);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • This is asked a lot. The wrong solution is to try to use a KeyListener -- never do that. Instead add a DocumentFilter to the JTextField's Document. – Hovercraft Full Of Eels Apr 30 '21 at 18:18
  • 1
    Use a JSpinner. Read the section from the Swing tutorial on [How to Use Spinners](https://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html). You can use a `SpinnerNumberModel` to control the range of values and the increment. – camickr Apr 30 '21 at 18:18
  • 1
    Yes, a JSpinner would work beautifully. Other unrelated issues are your use of `.setBounds(...)` which implies that you're using a null layout somewhere, something I strongly advise against, since it leads to GUI's that might not work on all platforms and that are hard to edit and enhance. Better to learn and use the layout managers. – Hovercraft Full Of Eels Apr 30 '21 at 18:27

0 Answers0