我已经创建了一个应用程序,它使用FocusListener来确保文本字段is的值始终为正。当用户输入负值,然后单击"tab“键将焦点从文本字段移开时,该值将乘以-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();
}}
发布于 2013-10-25 06:32:48
主要的问题是你在隐藏你的变量
你声明
JTextField posField = new JTextField("30",5);作为实例变量,但在构造函数中,您再次重新声明它...
public AlwaysPositive() {
//...
JTextField posField = new JTextField("30",5);
posField.addFocusListener(this);
//...
}Add将焦点侦听器附加到它,但在focusLost方法中,您引用的是实例变量,而不是屏幕上实际显示的实例变量
首先更改构造函数中的声明
public AlwaysPositive() {
//...
posField = new JTextField("30",5);
posField.addFocusListener(this);
//...
}然而,有比FocusListener更好的解决方案可以使用。
例如,您可以使用InputVerifier来验证字段的值,并决定是否应移动焦点。
特别看一下How to Use the Focus Subsystem和Validating Input
您还可以使用DocumentFilter来限制用户实际可以输入的内容,在用户键入输入时对其进行过滤。特别来看一下Text Component Features和Implementing a Document Filter。
您还可以查看these examples以获得更多想法
发布于 2013-10-25 06:53:48
在方法内创建同名对象时,侦听器将设置为方法对象,而不是类对象。
https://stackoverflow.com/questions/19577854
复制相似问题