如何为 JButton 编写鼠标移动事件

How to write mouse moved event for JButton

我尝试了以下程序来测试 java 鼠标适配器 class 的鼠标移动方法,但它没有用。当我将鼠标移到“鼠标悬停”按钮上时,我想将进度条的值从 2 增加。我该如何解决这个问题?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ProgressDemo extends JFrame{
    private JProgressBar progress;
    private JButton mouseButton;
    static int x = 2;
    ProgressDemo(){
        progress = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
        progress.setBounds(50,100,500,15);
        progress.setStringPainted(true);
        mouseButton = new JButton("Mouse Over");
        mouseButton.addMouseListener(new MouseAdapter(){
            public void mouseMoved(MouseEvent evt){
                progress.setValue(x+=2);
            }
        });


        JPanel mousePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        mousePanel.setBounds(0,10,600,50);
        mousePanel.add(mouseButton);

        setSize(600,200);
        setLayout(null);
        add(mousePanel);
        add(progress);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }
}

class JProgress{
    public static void main(String args[]){
        ProgressDemo p1 = new ProgressDemo();
        p1.setVisible(true);
    }
}

修改您的代码如下。希望对你的进步有所帮助。

mouseButton.addMouseMotionListener(new MouseMotionListener() {

     @Override
     public void mouseDragged(MouseEvent e) {
     }

     @Override
     public void mouseMoved(MouseEvent e) {
         progress.setValue(x += 2);
     }
});