KeyListener 不适用于 JTextField

发布于 12-12 21:14 字数 2906 浏览 0 评论 0原文

对不起我的英语。 我在使用 JTextField 和 KeyListener 时遇到一些问题。 我有下面的代码:

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

}

问题是监听器不起作用。可能是什么原因? 如果我添加鼠标侦听器它就可以工作。 提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

勿忘心安2024-12-19 21:14:52

不要为此使用 KeyListener。通常,如果我想在将更改放入 JTextField 后对更改做出反应,我会使用 DocumentListener 来侦听 JTextField 的文档,但即使这样也不太适合此类问题,因为您会尝试在字段完全填写之前以及最初在 JTextField 之一接收到任何数据之前进行计算。

更好的方法是向 GUI 添加 JButton,并在 JButton 的 ActionListener 中提取并解析 JTextField 中的文本,调用计算方法并显示计算结果。这样,您就不会得到过早的结果,而是仅在用户输入信息并确定输入的数据有效并且现在是进行计算的时间后才进行计算。您甚至可以禁用该按钮,直到两个 JTextField 都包含数据(DocumentListener 可以很好地实现此目的)。

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

旧人2024-12-19 21:14:52

对于 TextComponentsDocumentListener对于 NumbersJFormattedTextField,并且使用Number Formatter不允许仅输入数字和小数点分隔符,简单的示例 此处

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文