2013-03-22 105 views
1

好吧,我的問題是,當你拖動鼠標時,mouseMoved被凍結,這是MouseMotionListener(mouseMoved和mouseDragged)中的一種方法。我想也許mouseDragged凍結mouseMoved,如果任何人都可以幫助我,所以它不這樣做,那將是非常美妙的。EventListener凍結(Java)

import javax.swing.JFrame; 
import java.awt.Graphics; 
import java.awt.Image; 
import java.awt.event.MouseMotionListener; 
import java.awt.event.MouseEvent; 
import java.awt.Rectangle; 
import java.lang.Runnable; 
import java.awt.RenderingHints; 
import java.awt.Graphics2D; 
import java.awt.Color; 

public class Window extends JFrame implements MouseMotionListener, Runnable { 
    protected static int xWindow = 640; 
    protected static int yWindow = 480; 
    private Image dbi; 
    private Graphics dbg; 
    private int xMouse; 
    private int yMouse; 

    public void paint(Graphics g) { 
     dbi = createImage(getWidth(), getHeight()); 
     dbg = dbi.getGraphics(); 
     paintComponent(dbg); 
     g.drawImage(dbi, 0, 0, this); 
    } 

    public void paintComponent(Graphics g) { 
     Graphics2D g2d = (Graphics2D) g; 
     g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 
     g2d.setColor(Color.RED); 
     g2d.drawString("Mouse X: " + xMouse + " | Y: " + yMouse, 15, 40); 

     repaint(); 
    } 

    public void mouseDragged(MouseEvent e) { 
     e.consume(); 
    } 

    public void mouseMoved(MouseEvent e) { 
     xMouse = e.getX(); 
     yMouse = e.getY(); 
     e.consume(); 
    } 

    public void run() { 
     while (true) { 
      try { 
       Thread.sleep(1); 
      } catch(Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

} 

回答

2

你打電話repaintpaintComponent這會導致下面的方法調用鏈無限期地重複:

paint -> (manual call to) paintComponent 

採取Swing的優化油漆模式的優勢,最好不要做風俗畫中的頂級容器如JFrame。將所有繪畫功能提取到基於類的新的JComponentJPanel,並覆蓋paintComponent。 Swing將撥打paintComponentrepaint,因此無需直接撥打電話。不要忘記撥打super.paintComponent(g)

mouseMoved內呼叫repaint

也不要致電Thread.sleep,這會阻止EDT並導致UI凍結。 Swing提供自己的concurrency objects,如Swing Timers