我在模拟按钮单击时遇到问题。我有 JTextField
从扫描仪获取数据(就像在杂货店一样)。之后我需要按下 Enter 按钮来激活函数jTextField1ActionPerformed
。有没有办法在不产生任何按钮操作的情况下做到这一点?
或者我需要提示如何在每次 jTextField 更改时使用 jButton1.doClick() 。请帮忙!:)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
AddEmployee.add(jTextField1.getText());
jLabel7.setText(AddEmployee.name);
jLabel12.setText(AddEmployee.dep);
jLabel10.setText(AddEmployee.pos);
jLabel11.setText(AddEmployee.time);
num++;
jName.append("\n"+Integer.toString(num)+". "+AddEmployee.name);
jTime.append("\n"+Integer.toString(num)+". "+AddEmployee.time);
jTextField1.setText("");
}
catch (ClassNotFoundException | SQLException | ParseException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
最佳答案
如果你想模拟按钮按下,包括在UI中,你可以调用以下方法:
myButton.doClick();
这将在用户实际按下它时起作用。否则,您可以创建一个 ActionEvent 并将其传递给按钮的监听器:
// Does not appear in the UI
for(ActionListener a: mybutton.getActionListeners()) {
a.actionPerformed(yourActionEvent);
}
在你的情况下(考虑到发布的代码)我建议从按钮的代码中创建一个方法,然后在你想要的地方调用它:
public void showData(){
try {
AddEmployee.add(jTextField1.getText());
jLabel7.setText(AddEmployee.name);
jLabel12.setText(AddEmployee.dep);
jLabel10.setText(AddEmployee.pos);
jLabel11.setText(AddEmployee.time);
num++;
jName.append("\n"+Integer.toString(num)+". "+AddEmployee.name);
jTime.append("\n"+Integer.toString(num)+". "+AddEmployee.time);
jTextField1.setText("");
}
catch (ClassNotFoundException | SQLException | ParseException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void myButtonActionPerformed(java.awt.event.ActionEvent evt) {
showData();
}
private void myOtherComponentEventOcurred(java.awt.event.ActionEvent evt) {
showData();
}
关于java - 根据jtextfield的变化模拟按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26927483/