java - 根据jtextfield的变化模拟按钮点击

标签 java swing jbutton jtextfield

我在模拟按钮单击时遇到问题。我有 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/

相关文章:

java - 为什么我不能在我的 IntelliJ 中下载 OpenJDK-17?

java - Kotlin 通用反射子类

java - 如何在python中使用java编译的库?

java - 单击 GUI 时 JButton 消失

java - 如何遍历 swing 界面中的所有按钮?

java - 将图像放在 JButton 上方(而不是内部)并使 JButton 仍然工作

java - Jsoup 无法获取带有嵌套标签的外部 HTML

java - 如何使 JTable 列包含复选框?

java - jtree 让用户通过 "blinking"查看更新(颜色快速变化)

java - JButton 新手,如何让它们执行一个事件?