日期:2014-05-20  浏览次数:20694 次

java中关于paint()方法的问题
能说下我的paint()方法为什么没有被执行嘛,最好能详细点。paint()方法好像是自动被调用的。我写代码画不出东西来。帮调试下,说明下原因。非常感谢!!!

Java code

import java.awt.*;
import java.awt.event.*;

public class TestGraphics1 extends Frame{
    Frame f;
    Button b1;
    Button b2;

    TestGraphics1() {
        b1 = new Button("Draw Line");
        b2 = new Button("Draw circle");
        f = new Frame("Draw Graphics");
        f.setBounds(300,300,500,400);
        f.setVisible(true);
        f.setLayout(new FlowLayout());
        f.add(b1);
        f.add(b2);
        f.addWindowListener(new Monitor());
    }

    public void paint(Graphics g) {    
        Color c = g.getColor();
        g.setColor(Color.RED);
        g.drawLine(10,10,20,30);
        g.setColor(c);    
    }


    
    class Monitor extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }


    public static void main(String []args) {
        TestGraphics1 tg = new TestGraphics1();
    }
}



------解决方案--------------------
TestGraphics1中的paint()方法不是f的paint()方法,另外,你画的线会与标题栏重合绝大部分
Java code
import java.awt.*;
import java.awt.event.*;

public class TestGraphics1 extends Frame{
    Frame f;
    Button b1;
    Button b2;

    TestGraphics1() {
            super("Draw Graphics");
        b1 = new Button("Draw Line");
        b2 = new Button("Draw circle");
        setBounds(300,300,500,400);
        setLayout(new FlowLayout());
        add(b1);
        add(b2);
        
        addWindowListener(new Monitor());
        setVisible(true);
        
        //下面的paint()方法是TestGraphics1.this的paint方法,而不是f的
        /*f = new Frame("Draw Graphics");
        f.setBounds(300,300,500,400);
        f.setVisible(true);
        f.setLayout(new FlowLayout());
        f.add(b1);
        f.add(b2);
        f.addWindowListener(new Monitor());*/
    }

    public void paint(Graphics g) {  
        Color c = g.getColor();
        g.setColor(Color.RED);
        g.drawLine(100,100,20,30);
        //g.drawLine(10,10,20,30);坐标与标题栏重合了,如果仔细看的话,还是能在左上方看到一个红点的。。。
        g.setColor(c);    
    }


    
    class Monitor extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }


    public static void main(String []args) {
        TestGraphics1 tg = new TestGraphics1();
    }
}