namreg
namreg

Reputation: 53

KeyListener does not work with JTextField

Sorry for my English. I have some problems with JTextField and with KeyListener. I have the code below :

package com.gugnovich.tasks;   
@SuppressWarnings("serial")
public class Task1Panel extends Task {

    private static final String zLabel = "Please enter Z:";
    private static final String eLabel = "Please enter E:";
    private static final double K = 1.4;

    private JTextField zField;
    private JTextField eField;
    private JTextField result;

    private double zVal;
    private double eVal;
    private double resultVal;


    @Override
    protected void displayTaskPanel() {
        /** Panel settings */
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        setBorder(new EmptyBorder(10, 15, 10, 10));
        /** Add title of the task */
        JLabel title = new JLabel(Constants.TASK1_TITLE + ":");
        title.setFont(new Font("Monospaced", Font.BOLD, 18));
        add(title);
            /**
              Form builder
             */
        DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(""));
        builder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        builder.setBackground(Color.decode(Constants.BACKGROUND_COLOR));
            /**
              Add columns
             */
        builder.appendColumn("left:pref");
        builder.appendColumn("3dlu");
        builder.appendColumn("fill:max(pref; 100px)");

        builder.appendSeparator("Enter params");
            /**
              Field for Z
             */
        zField = new JTextField();
        builder.append(zLabel, zField);
        zField.addKeyListener(listener);
             /**
              Field for E
             */
        eField = new JTextField();
        builder.append(eLabel, eField, true);
        eField.addKeyListener(listener);

        builder.appendSeparator("Result");
            /**
               result field
            */
        result = new JTextField();
        result.setEnabled(false);
        result.setDisabledTextColor(Color.BLACK);
        builder.append("X = ", result);

        add(builder.getPanel());
    }
    /**
     listener
    */
    private KeyListener listener = new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            System.out.println("Typed");
            JTextField zf = (JTextField) e.getSource();
            zVal = Double.parseDouble(zf.getText());
            JTextField ef = (JTextField) e.getSource();
            eVal = Double.parseDouble(ef.getText());
            if (zVal > 0.00 && eVal > 0.00) {
                calculate();
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            System.out.println("Released");
        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("Pressed");
        }
    };

}

The problem is that the listener does not work. what could be the cause? If i will add mouse listener that it work. Thanks in advance.

Upvotes: 3

Views: 2656

Answers (2)

mKorbel
mKorbel

Reputation: 109815

for TextComponents is there DocumentListener and for Numbers is there JFormattedTextField, and with Number Formatter doesn't allows input only numbers and decimal separator, simple example here

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

Don't use a KeyListener for this. Often I'd use a DocumentListener to listen to the JTextField's Document if I wanted to react to changes after they've been placed in the JTextField, but even this is not a good fit for this type of problem since you'd be trying to calculate before the fields have been fully filled in, and initially before one of the JTextFields has received any data at all.

Much better would be to add a JButton to your GUI and in that JButton's ActionListener extract and parse the text from the JTextFields, call the calculate method and display the results of the calculation. This way you don't get premature results but rather will only do the calculations after the user has entered information and decided that the data entered is valid and now is the time to do calculations. You can even disable the button until both JTextFields contain data (a DocumentListener can work well for this).

Upvotes: 7

Related Questions