1

我创建了一个应用程序,它使用 FocusListener 来确保文本字段的值始终为正。当用户输入负值,然后单击“制表符”键将焦点从文本字段移开时,该值将乘以 -1,因此结果值为正值。但是,当我运行应用程序时,文本字段并没有改变。我不确定我做错了什么,并会感谢任何帮助。

这是我的代码:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class AlwaysPositive extends JFrame implements FocusListener {
JTextField posField = new JTextField("30",5);

public AlwaysPositive() {
    super("AlwaysPositive");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel pane = new JPanel();
    JTextField posField = new JTextField("30",5);
    JButton ok= new JButton("ok");
    posField.addFocusListener(this);
    pane.add(posField);
    pane.add(ok);
    add(pane);
    setVisible(true);
}

public void focusLost(FocusEvent event) {
    try {
        float pos = Float.parseFloat(posField.getText());
        if (pos < 0) 
            pos = pos*-1;
        posField.setText("" + pos);
    } catch (NumberFormatException nfe) {
        posField.setText("0");
    }
}

public void focusGained(FocusEvent event) {
}

public static void main(String[] arguments) {
    AlwaysPositive ap = new AlwaysPositive();
}

}

4

2 回答 2

1

当您在方法中创建同名对象时,侦听器将设置为方法对象而不是 Class 对象。

于 2013-10-24T22:53:47.613 回答
1

主要问题是你正在隐藏你的变量

你声明

 JTextField posField = new JTextField("30",5);

作为一个实例变量,但在你的构造函数中,你再次重新声明它......

public AlwaysPositive() {
    //...
    JTextField posField = new JTextField("30",5);
    posField.addFocusListener(this);
    //...
}

添加附加焦点侦听器,但在focusLost方法中,您指的是实例变量,它不是实际在屏幕上的那个

首先更改构造函数中的声明

public AlwaysPositive() {
    //...
    posField = new JTextField("30",5);
    posField.addFocusListener(this);
    //...
}

但是,有更好的解决方案可以使用 then FocusListener

例如,您可以使用InputVerifier允许您验证字段的值并决定是否应该移动焦点。

看看如何使用焦点子系统验证输入

您还可以使用 aDocumentFilter来限制用户实际可以输入的内容,在用户键入时过滤输入。看看Text Component FeaturesImplementing a Document Filter

您还可以查看这些示例以获取更多想法

于 2013-10-24T22:32:48.083 回答