import java.awt.*; import java.awt.event.*;public class MouseDraw extends Frame implements MouseMotionListener,MouseListener,ActionListener{ static MouseDraw frm=new MouseDraw(); int x1,x2,y1,y2; private static Color[] colors = { Color.white, Color.black, Color.blue, Color.red, Color.yellow, Color.orange, Color.cyan, Color.pink, Color.green }; static int i=1; Button btn1 = new Button("确定"); Panel p1 = new Panel(); Choice choice; MouseDraw() { setSize(400,440); setVisible(true); choice = new Choice(); choice.add("0.白色"); choice.add("1.黑色"); choice.add("2.蓝色"); choice.add("3.红色"); choice.add("4.黄色"); choice.add("5.橙色"); choice.add("6.灰色"); choice.add("7.粉红色"); choice.add("8.绿色"); btn1.addActionListener(this); p1.add(choice);p1.add(btn1); add(p1,BorderLayout.NORTH); addWindowListener(new WindowAdapter() { public void windowClosing (WindowEvent e) {System.exit(0);} } ); validate(); } public static void main(String args[]) { frm.setTitle("Free drawing"); frm.setSize(500,350); frm.addMouseListener(frm); frm.addMouseMotionListener(frm); frm.setVisible(true); } public void actionPerformed(ActionEvent ae) { int index= choice.getSelectedIndex(); this.i=index; } public void mousePressed(MouseEvent e) { x1=e.getX(); y1=e.getY(); } public void mouseDragged(MouseEvent e) { Graphics g=getGraphics(); x2=e.getX(); y2=e.getY(); g.setColor(colors[this.i]); g.drawLine(x1,y1,x2,y2); x1=x2; y1=y2; } public void mouseMoved(MouseEvent e){} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseClicked(MouseEvent e){}}
|