You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Swing密码键盘实现星号与按键数一致,按Enter不额外加星号

问题修复说明

根因定位

你代码的actionPerformed方法中,仅对按下CLEAR按键的场景做了跳过追加星号的处理,按下ENTER按键时没有对应拦截逻辑,导致每次点击ENTER都会触发星号追加的逻辑,产生多余的星号。

修复步骤

仅需要修改actionPerformed方法中的flag判断逻辑,将ENTER按键也加入跳过星号追加的范围即可,修改后的完整actionPerformed代码如下:

public void actionPerformed(ActionEvent e) {
    String textThere = display.getText(), textThereExtra = displayExtra.getText();
    String additionalText = "";
    for (int a = 0; a < buttonList.size(); a++) {
        if (e.getSource().equals(buttonList.get(a)) && a!=11 && a!=9) {
            additionalText = buttonList.get(a).getText();
        }
    }
    int flag = 0;
    // 新增ENTER按键的判断,CLEAR和ENTER都不触发星号追加
    if (e.getSource().equals(buttonList.get(9)) || e.getSource().equals(buttonList.get(11))) {
        if (e.getSource().equals(buttonList.get(9))) {
            // 只有CLEAR按键需要清空输入内容
            textThere = "";
            textThereExtra = "";
        }
        flag = 1;
    }
    if(flag!=1) {
        display.setText(textThere.concat("*"));
        displayExtra.setText(textThereExtra.concat(additionalText));
    }
    else
    {
        display.setText(textThere);
        displayExtra.setText(textThereExtra);
    }

    if (e.getSource().equals(buttonList.get(11))) {
        System.out.println(textThereExtra);
        System.out.println(textThere);
        if(textThereExtra.equals(PINCODE)) {
            Authorized();
        }
        else {
            Unauthorized();
        }
        // 可选补充:验证完成后自动清空输入
        display.setText("");
        displayExtra.setText("");
    }
}

额外注意事项

你代码中额外定义的clr和etr两个底部按钮目前没有绑定对应逻辑,点击这两个按钮也会触发星号追加。如果不需要这两个按钮可以直接删除相关代码;如果需要使用,参照上面的逻辑为这两个按钮也添加对应的flag判断即可。

内容的提问来源于stack exchange,提问作者eiriinjye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:27:01