java图形处理

//******************************************//

设计一个在窗体中可上下左右移动的小方块的程序

//******************************************//

public class Example extends JFrame implements ActionListener{

  JButton up = new JButton("向上移动");

  JButton down = new JButton("向下移动");

  JButton left = new JButton("向左移动");

  JBUtton right = new JButton("向右移动");

  MoveCanVas vas = new MoveCanVas();

  Example(){

    setSize(400,400);

    setLoction(500,100);

    setVisible(true);

    JPanel P = new JPanel();

    p.setLayout(new FlowLayout);

    setLayout(new BorderLayout);

    add(P,BorderLayout.SOUTH);

    add(vas,BorderLayout.CENTER);

    P.add(up);P.add(down);P.add(left);P.add(right);

    vlidate();

    left.addActionListener(this);

    right.addActionListener(this);

    up.addActionListener(this);

    down.addActionListener(this);

    addWindowListener(new WindowCloser());

  }

  public void actionPerformed(ActionEvent e){

    if(e.getSource == up)

      vas.moveUp();

    if(e.getSource == down)

      vas.moveDown();

    if(e.getSource == left)

      vas.moveLeft();

    if(e.getSource == right)

      vas.moveRight();

  }

  public static void main(String[] args){

    new Example();

  }  

}

class MoveCanVas extends Canvas{

  int WIDTH = 30, HEIGHT = 30, INC = 10;

  int j,i;

  public void paint(Graphics g){

    g.drawRect(0,0,getSize().width-1,getSize().height-1);

    g.setColor(Color.black);

    g.fillRect(i+2,j+2,WIDTH+2,HEIGHT+2);

    g.fillRect(i,j,WIDTH,HEIGHT); 

  }

  public void moveUp(){

    if(j>0)

      i-=INC;

    else

      j = getSize().height - INC;

    repaint();

}

  public void moveDown(){

    if(j<getSize().height-INC)

      j-=INC;

    else

      j = o;

    repaint();

  }

  public void moveLeft(){

    if(i>0)

      i-=INC;

    else

      i = getSize().width - INC

    repaint();

  }

  public void moveRight(){

    if(i<getSize().width - INC)

      i += INC;

    else

      i = 0;

    repaint();

  }

}

posted @ 2016-03-06 22:58  嘿壳  阅读(279)  评论(0编辑  收藏  举报