import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*;
public class Myframe1 extends JFrame { Mypanel1 p1; Mypanel2 p2; public Color c=Color.white; public Myframe1(String str) { super(str); p1=new Mypanel1(c,p2); p2=new Mypanel2(c); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(p1,BorderLayout.NORTH); this.getContentPane().add(p2,BorderLayout.CENTER); setSize(600,500); setVisible(true); } public static void main(String args[]) { new Myframe1("画图"); } } class Mypanel1 extends JPanel implements ActionListener { JButton b1,b2,b3,b4,b5; public Color c; Mypanel2 p2; public Mypanel1(Color c,Mypanel2 p2) { this.c=c; this.p2=p2; b1=new JButton("红色"); b2=new JButton("蓝色"); b3=new JButton("绿色"); b4=new JButton("橡皮"); b5=new JButton("清除"); this.add(b1); this.add(b2); this.add(b3); this.add(b4); this.add(b5); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { c=Color.red; } else if(e.getSource()==b2) { c=Color.blue; } else if(e.getSource()==b3) { c=Color.green; } else if(e.getSource()==b4) { c=Color.white; } else { p2.repaint(); } } } class Mypanel2 extends JPanel { public Color c; public Mypanel2(Color c) { this.c=c; this.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { Graphics g=getGraphics(); g.setColor(c);/*这里老报错*/ g.fillOval(e.getX(),e.getY(),3,3); } }); } public void paintComponent(Graphics g) { g.setColor(Color.white); g.fillRect(0,0,getSize().width,getSize().height); } }