鼠标坐标查找器GUI无法正常运行

时间:2015-09-19 00:33:24

标签: java jframe mouse

我想用JFrame创建一个程序,它允许你使用鼠标光标的最新坐标来启动和停止JLabel的更新。我无法弄清楚我做错了什么。请帮助并尊重。我是Java的新手,所以我无法帮助我做出的愚蠢错误。

以下是代码:

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


public class PrintPos extends JFrame {
    private static final long serialVersionUID = 7526472295622776147L;
    public JButton startBtn;
    public JButton stopBtn;
    public static JLabel posLabelX;
    public static JLabel posLabelY;
    static boolean started=false;

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


    PrintPos() {

        setLayout(new GridLayout(2,2));

        startBtn = new JButton("Start");
        stopBtn = new JButton("Stop");
        posLabelY = new JLabel("X:");
        posLabelX = new JLabel("Y:");

        add(startBtn);
        add(stopBtn);
        add(posLabelX);
        add(posLabelY);

        setSize(200,150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setLocationRelativeTo(null);

        startBtn.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent a)
          {
              started = true;
              while(started) {
                    PointerInfo inf = MouseInfo.getPointerInfo();
                    Point p = inf.getLocation();
                    posLabelX.setText(String.valueOf(p.x));
                    posLabelY.setText(String.valueOf(p.y));
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                    }
          }
        });

        stopBtn.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
              started = false;
          }
        });
    }

        public static void getInfo() {
            while(started) {
                PointerInfo inf = MouseInfo.getPointerInfo();
                Point p = inf.getLocation();
                posLabelX.setText(String.valueOf(p.x));
                posLabelY.setText(String.valueOf(p.y));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
                }
        }

}

1 个答案:

答案 0 :(得分:0)

您正在阻止事件调度线程。 EDT负责处理事件和绘制请求以及响应用户输入。当whileActionListener中运行时,EDT无法处理任何新事件,您的程序将“挂起”

有关详细信息,请查看Concurrency in Swing

看看Worker Threads and SwingWorkerHow to use Swing Timers提出一些解决方案的想法。

对于可运行的示例,请查看here