簡體   English   中英

在Swing中的鼠標懸停事件上停止線程

[英]Stopping Thread on Mouse Hover Event in Swing

我有一個桌面應用程序,其中將一個框架顯示為通知,但是當鼠標懸停在通知框架上時,我想停止該線程。 那我該怎么辦呢?

這是當前代碼:

final Notification not = new Notification();
Notification.notification_name.setText(msg[1]);

final ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
s.schedule(new Runnable() {

    public void run() {
        not.setVisible(false); //should be invoked on the EDT
        not.dispose();
    }
}, 6, TimeUnit.SECONDS);

正在顯示,並在6秒鍾后退出。

我正在嘗試的代碼。

final Notification not = new Notification();
not.addMouseListener(new MouseAdapter() {

    @Override
    public void mouseEntered(MouseEvent e) {
        try {
            super.mouseEntered(e);
            System.out.println("Mouse Entered");
            //s.wait();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(10000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        } catch (Exception x) {
            x.printStackTrace();
        }
    }

    @Override
    public void mouseExited(MouseEvent e) {
        try {
            super.mouseExited(e);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
});


final ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
s.schedule(new Runnable() {

    public void run() {
        not.setVisible(false); //should be invoked on the EDT
        not.dispose();
    }
}, 6, TimeUnit.SECONDS);

在此代碼中,通知幀將顯示到6秒鍾,但如果用戶將鼠標懸停在該幀上,則應一直顯示到用戶鼠標從該幀退出為止。

每當處理任何可能以某種方式影響UI的內容時,都需要小心並確保所有操作均在EDT上下文內完成。

javax.swing.Timer允許您在將來的某個時間設置回調,該回調在被觸發時將在EDT的上下文中被調用

import java.awt.BorderLayout;
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 java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class TimeExample {

    public static void main(String[] args) {
        new TimeExample();
    }

    public TimeExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(new TestPane());
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Timer timer;

        public TestPane() {
            setBorder(new LineBorder(Color.BLACK));

            timer = new Timer(6000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setBackground(Color.RED);
                }
            });
            timer.setRepeats(false);

            MouseAdapter ma = new MouseAdapter() {

                @Override
                public void mouseEntered(MouseEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();
                        setBackground(Color.BLUE);
                    }
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    if (!timer.isRunning()) {
                        timer.restart();
                        setBackground(UIManager.getColor("Panel.background"));
                    }
                }

                /**
                 * Testing purposes only!!
                 *
                 * @param e
                 */
                @Override
                public void mouseClicked(MouseEvent e) {
                    setBackground(UIManager.getColor("Panel.background"));
                    timer.restart();
                }

            };
            addMouseListener(ma);

            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(100, 100);
        }

    }

}

看看如何使用Swing計時器了解更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM