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. 但这个是临时的,最大化最小化后画的就没有了.