First thought: I did not follow the textbook and thought I could do it, but I did not pay for it for several days. I still had little knowledge, so I watched the textbook again.
The first is the layout:
import java.awt.*;import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; class Mycanvas extends Canvas{int x,y,r;Color c2;Mycanvas(){setBackground(Color.white);} public void get(int x){this.x = x;}public void get2(int y){this.y = y;}public void get3(int r){this.r = r;}public void paint(Graphics g){g.setColor(c2);g.fillOval(x, y,2*r,2*r);}public void update(Graphics g){g.clearRect(x, y,2*r,2*r);paint(g);}}
Then the main class:
Import Java. AWT. *; import Java. AWT. event. *; import javax. swing. *; public class Wancheng extends jframe implements itemlistener {mycanvas W; jcombobox C; Wancheng () {W = new mycanvas (); Panel p1 = new Panel (); C = new jcombobox (); C. additem ("Default signal"); C. additem ("red light"); C. additem ("yellow light"); C. additem ("green light"); p1.add (c); add (W, borderlayout. center); add (P1, borderlayout. north); C. additemlistener (this); setbounds (350,350,550,550); setvisible (true); Validate () ;}@ overridepublic void itemstatechanged (itemevent arg0) {// todo auto-generated method stubint d = C. getselectedindex (); If (D = 0) {W. get (100); W. get2 (1, 100); W. get3 (1, 100 );
}if (d == 1){w.get(100);w.get2(100);w.get3(100);w.c2 = Color.red;w.repaint();}if (d == 2){w.get(100);w.get2(100);w.get3(100);w.c2 = Color.yellow;w.repaint();}if (d == 3){w.get(100);w.get2(100);w.get3(100);w.c2 = Color.green;w.repaint();}}}
The last is the test class;
public class Test {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew Wancheng();}}