关于Component如何触发绘制

是在EventDispatchThread类中:

public void run() {
	try {
	    pumpEvents(new Conditional() {
		public boolean evaluate() {
		    return true;
		}
	    });	    
	} finally {
	    /*
	     * This synchronized block is to secure that the event dispatch 
	     * thread won't die in the middle of posting a new event to the
	     * associated event queue. It is important because we notify
	     * that the event dispatch thread is busy after posting a new event
	     * to its queue, so the EventQueue.dispatchThread reference must
	     * be valid at that point.
	     */
	    synchronized (theQueue) {
                if (theQueue.getDispatchThread() == this) {
                    theQueue.detachDispatchThread();
                }
                /*
                 * Event dispatch thread dies in case of an uncaught exception. 
                 * A new event dispatch thread for this queue will be started
                 * only if a new event is posted to it. In case if no more
                 * events are posted after this thread died all events that 
                 * currently are in the queue will never be dispatched.
                 */
                /*
                 * Fix for 4648733. Check both the associated java event
                 * queue and the PostEventQueue.
                 */
                if (theQueue.peekEvent() != null || 
                    !SunToolkit.isPostEventQueueEmpty()) { 
                    theQueue.initDispatchThread();
                }
		AWTAutoShutdown.getInstance().notifyThreadFree(this);
	    }
	}
    }

 

假设给这样一个测试类:

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;


class HelloWorldPanel extends JPanel {
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawString("Not a hello,World program", X, Y);
	}

	public static final int X = 75;
	public static final int Y = 100;
}

class HelloWorldFrame extends JFrame {
	public HelloWorldFrame() {
		setTitle("HelloWorld");
		setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		HelloWorldPanel panel = new HelloWorldPanel();
		getContentPane().add(panel);
	}

	public static final int DEFAULT_WIDTH = 300;
	public static final int DEFAULT_HEIGHT = 300;
}

public class TestHelloWorld {
	public static void main(String args[]) {
		HelloWorldFrame frame = new HelloWorldFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}
 

你可能感兴趣的:(开源轨迹)