我在使用Java Awt 的 Graphics类时,使用getGraphics()得到相关Component的Graphics context,然后在上面进行绘图,而不是采用重写paint()方法。但是遇到一个问题,必须在组件被实现后,调用Thread.sleep()方法才能使得之后的绘图线条显示出来。并且sleep()时间还不能太短。。比如我的程序Thread.sleep(100)可以,Thread.sleep(20)就不行了。完整代码如下:
- Java code
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(); }}
希望哪位大侠予以解释。。。。
------解决方案--------------------
理解的基本到位。
“我画上去的东西不消失,但是JButton给消失了”
public void paint(Graphics g) {
super.paint(g); // 增加这句话很重要,否则resize时就父类就没机会执行重绘了
g.setColor(Color.BLACK);
g.drawLine(5, 5, 15, 5);
}
当然还有一个负责特定控件重绘的函数是:paintComponents(Graphics g)
因为你没有把这个函数也给重写了,所以当“我鼠标移动到JButton所在位置时”,这个函数发挥效用了。