根据jtextfield的更改模拟按钮单击

时间:2014-11-14 10:09:23

标签: java swing jbutton jtextfield

我遇到按钮点击模拟的问题。我有JTextField从扫描仪获取数据(比如在杂货店)。之后我需要按下回车键,激活功能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);
    }  
}

1 个答案:

答案 0 :(得分:1)

如果您想模拟按下按钮,包括在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();
}