画笔程序说明
//In the last version I have finish the function to write a line ... //This version 0.2 will add more fun things... import java.awt.*; import javax.swing.*; import java.awt.event.*; public class DrawPad extends Frame { IDrawPad idp; JButton b1; JButton b2; JPanel jpl; public void init() { idp=new IDrawPad(this); jpl=new JPanel(new GridLayout(1,2,10,10)); b1=new JButton("Black"); b2=new JButton("Other"); //add(idp); add(idp,BorderLayout.CENTER); add(jpl,BorderLayout.NORTH); jpl.add(b1); jpl.add(b2); b1.addActionListener(idp); idp.init(); idp.setBackground(Color.magenta); this.setBackground(Color.white); this.setVisible(true); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String args[]) { new DrawPad().init(); } } class IDrawPad extends JPanel implements ActionListener{ DrawPad dp; IDrawPad(DrawPad dp) { this.dp=dp; } Color c=new Color(0, 150, 150); Point Frond=new Point(0,0); Point Back=new Point(0,0); Image tem; int i=1; boolean s_s; @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { if(i%4==3) { dp.b1.setLabel("CYAN"); c=Color.cyan; dp.b1.setBackground(c); i++; //System.out.println(i); } else if(i%4==2){ dp.b1.setLabel("Black"); c=Color.black; dp.b1.setBackground(c); i++; //System.out.println(i); } else if(i%4==1) { dp.b1.setLabel("RED"); c=Color.red; dp.b1.setBackground(c); i++; //System.out.println(i); } else if(i%4==0) { dp.b1.setLabel("BLUE"); c=Color.blue; dp.b1.setBackground(c); i++; //System.out.println(i); } } public void init() { setBounds(100,100,700,550); setBackground(Color.orange); setVisible(true); this.addMouseMotionListener(new MouseE()); this.addMouseListener(new MouseE()); } public void update(Graphics g) { if(tem==null) { tem=this.createImage(700, 550); } Graphics tg=tem.getGraphics(); paint(tg); g.drawImage(tem, 0, 0, null); } public void paint(Graphics g) { g.setColor(c); g.drawLine(Back.x, Back.y, Frond.x, Frond.y); Back=Frond; } } class MouseE extends MouseMotionAdapter implements MouseListener { IDrawPad y; @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { y=(IDrawPad)e.getSource(); //System.out.println(y.Back); y.Back=e.getPoint(); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public void mouseDragged(MouseEvent e) { y=(IDrawPad)e.getSource(); y.Frond=e.getPoint(); y.repaint(); } }
1.在最初,我直接在DrawPad上面作画,然后不断的update()这个画面....这样这个画面其实都是一个画板.但是实际中,我们只需要在一个画板区域作画...其他地方放置一个按键等功能...
2.所以我们需要在主窗口中添加一个可以画画的组件.也就是拥有paint()方法的一个组件...我们发现JPanel中有这个方法....所以我们新建一个IDrawPad从JPanel中继承...