JPanel 的getGraphics

转载http://www.cnblogs.com/qqjue/archive/2012/08/09/2630453.html

import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class TestPen extends JFrame {
    Graphics redPen ;
    public TestPen(){
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        final JPanel p = new JPanel();
        add(p,BorderLayout.CENTER);
        JButton bt = new JButton("获取画笔");
        bt.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                redPen = getGraphics();
                //redPen = p.getGraphics();也OK
                redPen.setColor(Color.RED);
            }
        });
        add(bt,BorderLayout.SOUTH);
        p.setBorder(BorderFactory.createTitledBorder("PP"));
        addMouseMotionListener(new MouseAdapter(){
            public void mouseDragged(MouseEvent e ) {
                if (redPen==null) return;
                redPen.fillOval(e.getX(), e.getY(), 5, 5);
            }
        });
        setVisible(true);
    }
    public void init(){
        redPen = getGraphics();
        redPen.setColor(Color.RED);
        addMouseMotionListener(new MouseAdapter(){
            public void mouseDragged(MouseEvent e ) {
                redPen.fillOval(e.getX(), e.getY(), 10, 10);
            }
        });
    }
    public static void main(String[] args ) {
        
        new TestPen();
        
    }

}


因为在所有组件还没画出时,是不能获得Graphics的,只会返回空.只有在JFrame全部显示后才能get到Graphics.所以把他们放到事件中,手动获得.就可以.这样画图也不用重写paint. 但这个是临时的,最大化最小化后画的就没有了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值