java - 带 Swing GUI 的 IndexOutOfBounds 跟踪鼠标

标签 java swing listener mouse-listeners

我不明白为什么我编写的这个简单程序在鼠标离开跟踪区域(白色 JPanel)时尝试更新鼠标坐标时会出现 IndexOutOfBounds 异常。我以为第 38 行的检查会解决这个问题。有什么建议么?谢谢!

import java.awt.*;

import javax.swing.JFrame;

public class MainFrame extends JFrame {

    private static final long serialVersionUID = 1L;

    Label coorLabel;
    Panel coorPanel, content;

    public MainFrame(String s){

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container cont = getContentPane();

        coorLabel = new Label("Mouse Coordinates: ");

        coorPanel = new Panel();
        coorPanel.setPreferredSize(new Dimension(400,400));
        coorPanel.setBackground(Color.WHITE);
        /**
        content = new Panel();
        content.add(coorPanel, BorderLayout.PAGE_START);
        content.add(coorLabel, BorderLayout.PAGE_END);
        **/

        cont.add(coorPanel, BorderLayout.PAGE_START);
        cont.add(coorLabel, BorderLayout.PAGE_END);

        pack();
        setVisible(true);

    }

    public void updateCoor(){

        if(coorPanel.getMousePosition()!=null){
            coorLabel.setText("Mouse Coordinates: "+getMousePosition().x+", "+getMousePosition().y);
            coorLabel.repaint();
        }

    }

    public static void main(String[]args){

        MainFrame frame = new MainFrame("Coor App");
        while(true){
            frame.updateCoor();
        }

    }

}

最佳答案

看看Concurrency in Swing教程。你完全占据了一开始 带有 while(true) 循环的线程,并在事件调度线程之外更新用户界面。

参见Introduction to Event Listeners熟悉 Swing 事件模型和 How to Write a Mouse-Motion Listener特别是对于鼠标运动监听器示例。

关于java - 带 Swing GUI 的 IndexOutOfBounds 跟踪鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272674/

相关文章:

java - 如何在不破坏 Android 的情况下将 Eclipse 工作区组织到文件夹中

java - 使用 GeoJson 向 google map 添加标记

java - Android MediaPlayer 创建失败

java - 将一个 GUI 面板中的用户输入显示在另一个 GUI 面板上

java - 与听众一起改变变量

spring - 使用 ServletContextListener 进行单元测试

java - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : and executeUpdate won't work

Java:如何更改 2x2 GridLayout 中 JLabels 的顺序?

Java - 通过单个文本字段将多个值输入到数组中

Java 监听器继承