【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);}}
吐了吐了吐了
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
