- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
美好的一天!
我正在制作一个出勤检查程序,单击一次时显示橙色按钮,单击两次时显示红色按钮,单击 3 次时显示黑色按钮。我在如何累积 getClickCount() 值方面遇到问题,因为对于按钮要注册 3 次点击,按钮必须快速点击 3 次。
这是代码
button1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent a){
if (a.getClickCount() == 1){
button1.setBackground(Color.ORANGE);
}
else if (a.getClickCount() == 2){
button1.setBackground(Color.RED);
}
else if (a.getClickCount() == 3){
button1.setBackground(Color.BLACK);
}
}
});
frame.setVisible(true);
frame.pack();
}
}
最佳答案
如果我理解正确的话,基本上你想在每次按下按钮时根据之前按下按钮的次数来更改颜色。
MouseListener
对于 JButton
来说不是一个好的选择,因为按钮可以通过键盘(通过快捷键或焦点 Activity )和编程方式激活,其中没有一个 MouseListener
将检测到。
相反,您应该使用 ActionListener
此示例将在每次单击按钮时更改颜色。我使用了 Color
数组来让生活变得更简单,但一般概念应该适用于 if-else
语句,您只需要在计数器达到它的极限
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ButtonClicker {
public static void main(String[] args) {
new ButtonClicker();
}
public ButtonClicker() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
private static final Color[] COLORS = new Color[]{Color.ORANGE, Color.RED, Color.BLACK};
private int clickCount;
public TestPane() {
setLayout(new GridBagLayout());
JButton clicker = new JButton("Color Changer");
clicker.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
setBackground(COLORS[Math.abs(clickCount % COLORS.length)]);
}
});
setBackground(COLORS[clickCount]);
add(clicker);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
看看How to Use Buttons, Check Boxes, and Radio Buttons和 How to Write an Action Listeners了解更多详情
关于java - 累积 getClickCount(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006029/
美好的一天! 我正在制作一个出勤检查程序,单击一次时显示橙色按钮,单击两次时显示红色按钮,单击 3 次时显示黑色按钮。我在如何累积 getClickCount() 值方面遇到问题,因为对于按钮要注册
private class MouseClickhandler extends MouseAdapter{ public void mouseClicked(MouseEvent event)
我是一名优秀的程序员,十分优秀!