方块移动
package result;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class F8 extends JFrame implements ActionListener{
	private JButton left = new JButton("向左移");
	private JButton right = new JButton("向右移");
	private JButton up = new JButton("向上移");
	private JButton down = new JButton("向下移");
	//创建4个按钮
	public MoveCanvas drawing = new MoveCanvas();
	//实例化画布,绘制图形块
	
	//内部类做监听器
	private class WindowCloser extends WindowAdapter{
		//创建接受窗体事件的适配器
		public void windowClosing(WindowEvent we) {
			System.exit(0);
		}
	}
	public F8() {
		super("移动方块");
		setSize(400,400);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		JPanel panel = new JPanel();//定义一个面板
		panel.setLayout(new FlowLayout());
		add(panel,BorderLayout.SOUTH);
		add(drawing,BorderLayout.CENTER);
		panel.add(up);
		panel.add(down);
		panel.add(left);
		panel.add(right);
		validate();
		//注册事件监听器
		left.addActionListener(this);
		right.addActionListener(this);
		up.addActionListener(this);
		down.addActionListener(this);
		addWindowListener(new WindowCloser());
	}
	public void actionPerformed(ActionEvent e) {
		if (e.getSource()==up) 
			drawing.moveUp();
		else if (e.getSource()==down) {
			drawing.moveDown();
		}
		else if (e.getSource()==left) {
			drawing.moveLeft();
		}
		else if (e.getSource()==right) {
			drawing.moveRight();
		}
	}
	
	
	public static void main(String[] args) {
		JFrame.setDefaultLookAndFeelDecorated(true);
		new F8();
	}
}
//创建一个绘制可移动的方块的画布类
class MoveCanvas extends Canvas{
	int WIDTH = 30,HEIGHT = 30,INC = 10;
	//设置方块的大小,INC为每次移动方块的步长值
	int i,j;
	public void paint(Graphics g) {
		g.drawRect(0, 0, getSize().width-1, getSize().height-1);
		//方块随着i,j移动
		g.setColor(Color.black);
		g.fillRect(i+2, j+2, WIDTH+2, HEIGHT+2);
		//移动之前的颜色方块
		g.setColor(Color.red);
		g.fillRect(i, j, WIDTH, HEIGHT);
		//移动之后的红色方块
	}
	public void moveUp()
	{
		//图形块位置在垂直方向上减少,从而实现图形块向上移动
		if (j>0) {
			j -= INC;
		}
		else {
			j = getSize().height - INC;
		}
		repaint();
	}
	public void moveDown()
	{
		if (j<getSize().height - INC) {
			j += INC;
		}
		else {
			j = 0;
		}
		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();
	}
}


 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号