我不明白爲什麼我寫這個簡單的程序,當鼠標離開跟蹤區域(白色JPanel)時試圖更新鼠標的座標時,得到一個IndexOutOfBounds異常。我認爲38號線的支票會照顧它。有什麼建議麼?謝謝!IndexOutOfBounds跟蹤鼠標與鞦韆gui
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();
}
}
}
爲什麼不使用MouseMotionListener及其mouseMoved();方法來捕捉位置? –