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

Java Swing按钮每次按下触发不同动作的计分器开发问题问询

实现方案

你需要补充计数展示组件、组件初始化逻辑以及点击事件响应逻辑,完整可运行代码如下:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyFrame extends JFrame implements ActionListener{
    
    JButton button;
    JButton button2;
    JLabel countLabel; // 用于展示计数的展示组件
    
    int clicked1Count = 0;
    int clicked2Count = 0;

    // 构造方法完成窗口和组件初始化
    public MyFrame() {
        // 窗口基础属性配置
        setTitle("小型计分器");
        setSize(300, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20));

        // 初始化按钮并绑定点击事件
        button = new JButton("按钮1计数+1");
        button2 = new JButton("按钮2计数+1");
        button.addActionListener(this);
        button2.addActionListener(this);

        // 初始化计数展示标签
        countLabel = new JLabel("按钮1计数:0 | 按钮2计数:0");

        // 组件挂载到窗口
        add(button);
        add(button2);
        add(countLabel);

        setVisible(true);
    }

    // 重写点击事件处理方法
    @Override
    public void actionPerformed(ActionEvent e) {
        // 区分点击的按钮,累加对应计数
        if(e.getSource() == button) {
            clicked1Count++;
        } else if(e.getSource() == button2) {
            clicked2Count++;
        }
        // 更新展示的计数值
        countLabel.setText(String.format("按钮1计数:%d | 按钮2计数:%d", clicked1Count, clicked2Count));
    }

    // 主方法启动程序
    public static void main(String[] args) {
        new MyFrame();
    }
}

核心逻辑说明

  • 新增JLabel类型的countLabel组件专门用于实时展示两个按钮的计数值,你也可以根据需求替换成文本框等其他展示组件
  • 构造方法中完成了所有组件的初始化、事件绑定和窗口配置,可自行调整按钮文本、窗口尺寸、布局样式等参数适配你的需求
  • actionPerformed方法中通过e.getSource()区分触发事件的按钮,累加对应计数变量后直接修改展示组件的文本即可实现计数实时更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:39:03