To draw and move a Car in java Graphics and control it using button
To draw and move a Car in java Graphics and control it using button
back :- for moving backward
forward :- for moving forward
stop :- to stop
output:-
back :- for moving backward
forward :- for moving forward
stop :- to stop
Program :-
01 | import java.applet.*; |
02 | import java.awt.*; |
03 | import java.awt.event.*; |
04 | /*<applet code="frame2" height=200 width=400> |
05 | </applet>*/ |
06 | public class frame2 extends Applet implements ActionListener |
07 | { int x; int y; int w;int t1,t2; |
08 | Button b1;Button b2;Button b3; |
09 | String msg=" "; |
10 | void slep() //for delay |
11 | { |
12 | try { |
13 | Thread.sleep(100); |
14 | }catch(Exception ex) { |
15 | } |
16 | } |
17 | public void init() |
18 | { |
19 | t1=0;t2=1; |
20 | y=60; |
21 | x=20; |
22 | setLayout(new FlowLayout(FlowLayout.CENTER)); |
23 | Label l=new Label("Anupam"); |
24 | b1=new Button("back"); |
25 | add(b1); |
26 | b2=new Button("forward"); |
27 | b3=new Button("stop"); |
28 | add(b3);add(b2); |
29 | b1.addActionListener(this); |
30 | b2.addActionListener(this); |
31 | b3.addActionListener(this); |
32 | } |
33 |
34 | public void start() |
35 | { |
36 | } |
37 | public void actionPerformed(ActionEvent e) |
38 | { |
39 | String s=e.getActionCommand(); |
40 | if(s.equals("back")) |
41 | { |
42 | msg="back"; |
43 | repaint(); |
44 | } |
45 | else if(s.equals("forward")) |
46 | { |
47 | msg="forward"; |
48 | repaint(); |
49 | } |
50 | else if(s.equals("stop")) |
51 | { |
52 | msg=" ";repaint(); } |
53 | } |
54 | public void paint(Graphics g) |
55 | { |
56 | setBackground(Color.cyan); |
57 | w=getWidth(); |
58 | Color c1=new Color(20,160,200); |
59 | Color c2=new Color(200,60,200); |
60 | g.setColor(c1); |
61 | g.drawLine(0,y+75,w,y+75); |
62 | g.setColor(c2); |
63 | g.fillRoundRect(x,y+20,100,40,5,5); |
64 | g.fillArc(x+90,y+20,20,40,270,180); |
65 | g.setColor(c1); |
66 | g.fillRoundRect(x+10,y,70,25,10,10); |
67 | g.setColor(Color.white); |
68 | g.fillRect(x+20,y+5,20,25); |
69 | g.fillRect(x+50,y+5,20,25); |
70 | g.setColor(Color.black); |
71 | g.fillRoundRect(x+55,y+10,10,20,10,10); |
72 | g.fillOval(x+10,y+50,25,25); |
73 | g.fillOval(x+60,y+50,25,25); |
74 | g.setColor(Color.white); |
75 | g.fillArc(x+20,y+60,5,5,0,360); |
76 | g.fillArc(x+70,y+60,5,5,0,360); |
77 | slep(); |
78 | if(msg.equals("forward")) |
79 | { |
80 | if(x+120<w) |
81 | { |
82 | x=x+1; |
83 | showStatus("press back for moving backward"); |
84 | repaint(); |
85 | } |
86 | } |
87 | if(msg.equals("back")) |
88 | { |
89 | if(x>0) |
90 | { |
91 | x=x-1; |
92 | showStatus("press forward for moving forward"); |
93 | repaint();} |
94 | } |
95 | } |
96 | } |
output:-
C:\java>javac frame2.java
C:\java>appletviewer frame2.java
No comments:
Post a Comment