【Java】编写一个界面程序,实现小车的移动

这里写目录标题

目的

编写一个界面程序,包含四个按钮,“向上移”,“向下移”,“向左移”,“向右移”界面中间显示一个小车(有一个矩形和两个圆形组成),点击“向上移”,“向下移”,“向左移”,“向右移”实现小车的移动。

代码

package login;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class car extends JFrame implements ActionListener 
{
	static Graphics g ;
	JButton bup,bdown,bleft,bright;
	int rx0=50;
	int ry0=50;
	int oy0=75;
	int ox0=60;
	int oy1=75;
	int ox1=90;
	public car()
	{
		setTitle("小车");
		setSize(500,500);
		setLocation(200,400);
		setVisible(true);
		this.setLayout(new BorderLayout());
		//加按钮
		JPanel buts = new JPanel();
		buts.setLayout(new GridLayout(1,4));
		bup=new JButton("向上移");
		bdown= new JButton("向下移");
		bleft = new JButton("向左移");
		bright = new JButton("向右移");
		buts.add(bup);
		buts.add(bdown);
		buts.add(bleft);
		buts.add(bright);
		add(buts,"South");
		//注册响应
		bup.addActionListener(this);
		bdown.addActionListener(this);
		bleft.addActionListener(this);
		bright.addActionListener(this);
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if(e.getSource()==bup)
		{
			ry0-=10;
			oy0-=10;
			oy1-=10;	
			this.repaint();
			//paint(g);
		}
		else if(e.getSource()==bdown)
		{
			
			ry0+=10;
			oy0+=10;
			oy1+=10;
			this.repaint();
			//paint(g);
		}
		else if(e.getSource()==bleft)
		{
			rx0-=10;
			ox0-=10;
			ox1-=10;
			this.repaint();
			//paint(g);
		}
		else if(e.getSource()==bright)
		{
			rx0+=10;
			ox0+=10;
			ox1+=10;
			this.repaint();
			//paint(g);
		}
	}
	
	public  void paint(Graphics g)//画车
	{
		super.paint(g);
		g.setColor(Color.black);
		g.drawRect(rx0, ry0, 70, 30);
		g.drawOval(ox0, oy0, 20, 20);
		g.drawOval(ox1, oy1, 20, 20);
	}
	
	public  static void main (String args[])
	{
		car c=new car();
		c.paint(g);
	}

}

吐了吐了吐了

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值