EventListener Freezing(Java)

时间:2013-03-22 04:27:18

标签: java swing jframe

好吧,我的问题是当您拖动鼠标时mouseMoved被冻结,这是MouseMotionListener(mouseMoved和mouseDragged)中的方法之一。我想也许mouseDragged会冻结mouseMoved,如果有人可以帮助我,那么它就不会那么做了,那将是非常精彩的。

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();
            }
        }
    }

}

1 个答案:

答案 0 :(得分:2)

您从repaint调用paintComponent会导致以下方法调用链无限重复:

paint -> (manual call to) paintComponent 

要利用Swing优化的绘画模型,最好不要在JFrame等顶级容器中进行自定义绘画。将所有绘画功能提取到基于JComponentJPanel的新课程并覆盖paintComponent。 Swing会在paintComponent上拨打repaint,因此无需直接致电。不要忘记致电super.paintComponent(g)

repaint内拨打mouseMoved

也不要调用Thread.sleep,这会阻止EDT并导致用户界面冻结。 Swing提供了自己的concurrency objects,例如Swing Timers