Java getGraphics()的用法是否涉及线程同步啊?
我在使用Java Awt 的 Graphics类时,使用getGraphics()得到相关Component的Graphics context,然后在上面进行绘图,而不是采用重写paint()方法。但是遇到一个问题,必须在组件被实现后,调用Thread.sleep()方法才能使得之后的绘图线条显示出来。并且sleep()时间还不能太短。。比如我的程序Thread.sleep(100)可以,Thread.sleep(20)就不行了。完整代码如下:
package com.han;import java.awt.Color;import java.awt.Container;import java.awt.FlowLayout;import java.awt.Graphics;import javax.swing.JButton;import javax.swing.JFrame;public class Graphics_1 extends JFrame { /** * */ private static final long serialVersionUID = -5861565474703590207L; JButton button = new JButton("JButton"); Container container; public Graphics_1() { // TODO Auto-generated constructor stub container = getContentPane(); container.setLayout(new FlowLayout()); container.add(button); } void paintJButton() { /* * Creates a graphics context for Container (you can also try it for * JFrame) */ Graphics g = container.getGraphics(); g.setColor(Color.BLACK); /* * Draws a line, using the current color, between the points (x1, y1) * and (x2, y2) in this graphics context's coordinate system. */ g.drawLine(5, 5, 15, 5); System.out.println("here"); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub final Graphics_1 frame = new Graphics_1(); frame.setTitle("Painting figures on the JButton"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(100, 100, 300, 200); frame.setVisible(true); try { Thread.sleep(100); // Thread.sleep(20); does not work ! } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } frame.paintJButton(); }}