我有一个只有Jtextfield
的面板,只接受数字。因此,当我按Enter键将加载用户个人资料。这只是为了看他的个人资料。
我想要的是:当我再次按下ENTER时,所有配置文件都将被清除,当我按下数字并再次按下ENTER并再次加载配置文件时......
我的问题:我按了回车键并清除了配置文件(确定一切正常),但是当我输入数字并按下ENTER时,数字被清除且没有任何反应,就像matriculaTxt.addKeyListener(new KeyAdapter() { ... }
中的循环一样
抱歉我的英语不好。
private void matriculaTxtActionPerformed(java.awt.event.ActionEvent evt)
{
String matricula = matriculaTxt.getText().trim();
if (!matricula.matches("[0-9]+")) {
matriculaTxt.setText("");
} else {
fc = new FrequenciaController();
matriculaTxt.setEditable(false);
matriculaTxt.requestFocus();
fc.checkinManual(Integer.parseInt(matricula));
}
// the problem is here.
matriculaTxt.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
nomeTxt.setText("");
statusTxt.setText("");
imageLb.setIcon(null);
acessoLabel.setText("");
matriculaTxt.setText("");
observacaoTxt.setText("");
System.err.println("ENTER");
PendenciasTableModel ptm = new PendenciasTableModel();// vazio
pendenciasTabela.setModel(ptm);
matriculaTxt.setEditable(true);
matriculaTxt.requestFocus();
}
}
});
}
我想做的很简单。用户在文本字段中键入其数字,按ENTER键:加载其数据。 requestFocus()
进入文本字段,它将不再可编辑,因为当我再次按Enter时,该字段将是可编辑的,但所有内容都将被删除,依此类推。
答案 0 :(得分:4)
首先,你不应该为这种事情使用KeyListener。请考虑使用JFormattedTextField或使用DocumentFilter来防止非数字输入。接下来,您应该使用ActionLIstener让JTextField接受并响应用户按Enter键。
修改强>
你说:
我的确切要求是,当我再次按下ENTER时,将清除所有数据以插入新数据。
为什么不简单地使用JTextField的ActionLIstener:
@Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText();
// do what you want with text here
// clear the text
textComp.setText("");
}
同样,你不应该为任何这些东西使用KeyListener。
编辑2
如果你想要一个多状态动作监听器,一个根据程序状态做出不同反应的监听器,然后给它一些if块,以允许它对JTextField的状态做出反应。如果字段为空,则执行一项操作,如果有数字,则执行另一项操作,如果有文本,则显示警告并清除它:
@Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText().trim(); // trim it to rid it of white space
if (text.isEmpty()) {
// code to show a profile
return; // to exit this method
}
// if we're here, the field is not empty
if (!text.matches("[0-9]+")) {
// show a warning message here
} else {
// numeric only data present
// do action for this state
}
// clear the text
textComp.setText("");
}
键再次是不使用KeyListener,而是使用ActionListener 仅来“监听”回车键,但是根据程序的状态做出不同的反应,这里可能取决于JTextField中存在的内容。
答案 1 :(得分:0)
我认为你的问题是KeyListener
它不会触发,它不会执行其中的代码,因为无论何时按ENTER
它都会触发matriculaTxtActionPerformed
然后声明KeyLister
,所以ENTER
会影响它。