简体   繁体   English

KeyListener不适用于JTextField

[英]KeyListener does not work with JTextField

Sorry for my English. 对不起我的英语不好。 I have some problems with JTextField and with KeyListener. 我在使用JTextField和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. 提前致谢。

Don't use a KeyListener for this. 不要为此使用KeyListener。 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. 通常我会使用DocumentListener来监听JTextField的文档,如果我想在将它们放入JTextField后对它做出反应,但即使这样也不适合这类问题,因为你要尝试在字段完全填入之前计算,并且最初在其中一个JTextField完全接收到任何数据之前计算。

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. 更好的方法是将JButton添加到GUI中,并在JButton的ActionListener中提取并解析来自JTextFields的文本,调用calculate方法并显示计算结果。 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). 您甚至可以禁用该按钮,直到两个JTextField都包含数据(DocumentListener可以很好地工作)。

对于TextComponentsDocumentListener ,对于NumbersJFormattedTextField ,而Number Formatter不允许只输入数字和小数分隔符,这里的简单示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM