我有一个空的 JTextField,用户应该使用 int 数字对其进行修改。但是,即使 JTextFiled 已填充了整数,当我从该 JTextField 获取字符串时,字符串结果为“”(-> 空)。 我怎样才能保存该字段的新值?我应该怎么办? 问题是这样的:
//Class where JTextField is initialized:
javax.swing.JTextField tMax = new javax.swing.JTextField();
tMax.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
tMaxKeyTyped(evt);
}
});
private void tMaxKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
char c = evt.getKeyChar();
if(!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_DELETE)) {
getToolkit().beep();
evt.consume();
}
}
public String getTMax() {
String tMaxString = tMax.getText();
return tMaxString;
}
//Class where tMax should be used
//code
private void runBtnActionPerformed(java.awt.event.ActionEvent evt) {
Panel class1 = new Panel();
String tMaxString = class1.getTMax();
System.out.println(tMaxString);
当我运行程序并单击“运行”按钮时,Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
.
如何保存修改后的 JTextField? 非常感谢。
最佳答案
您的 tMax 字段定义了两次。一次作为实例变量,一次作为局部变量。
摆脱局部变量:
//javax.swing.JTextField tMax = new javax.swing.JTextField();
tMax = new javax.swing.JTextField();
even once the JTextFiled has been filled with an integer,
不要使用 KeyListener 来编辑键入的文本。相反,您应该使用:
关于java - 如何获取用户修改后的 JTextField 的值 [java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36017005/