我不明白为什么我编写的这个简单程序在鼠标离开跟踪区域(白色 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/