Search code examples
javaswingkeypress

how to fix key pressed function for changing Jlabel into valid values


I'm working with conversion degrees, once user enters value into text field pointing out which degree is needed, the input with output result should appear instead of the label was before. Here section for formatting restriction for letters input only for numbers in the text field

        NumberFormat format = NumberFormat.getInstance();
        NumberFormatter formatter = new NumberFormatter(format);
        formatter.setValueClass(Double.class);
        formatter.setMinimum(Double.MIN_VALUE);
        formatter.setMaximum(Double.MAX_VALUE);
        formatter.setAllowsInvalid(false);
        formatter.setCommitsOnValidEdit(true);
        formattedTextField = new JFormattedTextField(formatter);

        formattedTextField.setColumns(10);

      }

here the problem

      public void keyPressed(KeyEvent e){
        double degree;
        if (Angle.isSelected()||e.getKeyChar()==KeyEvent.VK_ENTER){
          degree = Math.toDegrees((double)formattedTextField.getValue());
          resultLabel.setText(formattedTextField.getValue() 
   + " ° = "+ degree + " radians");

  }else if(Radians.isSelected()||e.getKeyChar()==KeyEvent.VK_ENTER){
 degree = Math.toRadians((double) formattedTextField.getValue());
          resultLabel.setText(formattedTextField.getValue() + 
 " radians = " + degree + " °");
        }
      }
    }

Solution

  • The problem is that you’re using || (or) instead of && (and). Your if tests don’t require the key being pressed to be ENTER; they require that the key is ENTER, or one of the radio buttons (Angle or Radians) is selected.

    All that said… it doesn’t matter, because you should not use a KeyListener for this. Normally, you check for the user pressing Enter in a JTextField by adding an ActionListener, but JFormattedTextField has a better way, which monitors not only Enter but also loss of focus: the documentation for JFormattedTextField’s value property states that it is a bound property, which means you can listen to changes in that property:

    formattedTextField.addPropertyChangeListener("value",
        new PropertyChangeListener() {
            @Override
            public void propertyChangeEvent(PropertyChangeEvent event) {
                Double newValue = (Double) event.getNewValue();
                if (newValue != null) {
                    if (angle.isSelected()) {
                        double radians = Math.toRadians(newValue);
                        resultLabel.setText(
                            newValue = + " ° = " + radians + " radians");
                    } else {
                        double degree = Math.toDegrees(newValue);
                        resultLabel.setText(
                            newValue + " radians = " + degree + " °");
                    }
                }
            }
        });