gpt4 book ai didi

java - 点击计数器 Java GUI

转载 作者:行者123 更新时间:2023-12-01 10:28:15 24 4
gpt4 key购买 nike

这个程序应该计算鼠标点击次数,但它只计算第一次。帮助!!这段代码并不复杂,但我不明白为什么它只计算第一次点击。我停止点击后它也会重置

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ClickCounter {

private JFrame frame;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClickCounter window = new ClickCounter();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public ClickCounter() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 226, 188);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JLabel lblNumber = new JLabel("Number of Mouse Clicks = 0");
lblNumber.setFont(new Font("Sitka Text", Font.BOLD | Font.ITALIC, 13));
lblNumber.setBounds(10, 11, 190, 28);
frame.getContentPane().add(lblNumber);

JPanel panel = new JPanel();
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int count = e.getClickCount();
lblNumber.setText("Number of Mouse Clicks = "+ count);
}
});
panel.setBounds(0, 35, 210, 114);
frame.getContentPane().add(panel);
}
}

最佳答案

MouseEvent.getClickCount() 不是绝对点击计数器 - 它只是计算您快速连续点击的频率(以区分单击和双击)。

您需要一个单独的计数器字段,您可以在 MouseListener 中增加该字段。

<小时/>

你可以这样实现:

public class ClickCounter {
private JFrame frame;
private int count;

然后在初始化方法中

    panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
count++;
lblNumber.setText("Number of Mouse Clicks = "+ count);
}
});

关于java - 点击计数器 Java GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com