Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Applets- creating a interactive traffic light without using 'canvas'?
    primarykey
    data
    text
    <p>To make it short I want to design a java applet that shows a traffic light with three adjacent buttons. One that says red light, one that says amber light and one for green.</p> <hr> <p>My problem is: is that I don't know how to link each button with the right oval. All of the ovals belong to the same Graphics variable g. If I change the color all three would be changed. </p> <p>There is a superclass called canvas that helps separate each object in its own entity from my knowledge but I know there is an easier way. </p> <p>How can I do this?</p> <pre><code>import java.awt.*; import java.awt.event.*; import java.applet.*; import java.applet.Applet; public class Traffic extends Applet implements ActionListener { int colourNum; //global variable which is responible for changing the light Button bttn1 = new Button ("Stop Traffic"); Button bttn2 = new Button ("Caution"); Button bttn3 = new Button ("Proceed"); public void init () { setBackground (Color.lightGray); bttn1.addActionListener (this); // stop light bttn2.addActionListener (this); // yellow light bttn3.addActionListener (this); // green light add (bttn1); add (bttn2); add (bttn3); } public void paint (Graphics g) // responsible for graphics "within" the window { g.setColor (Color.black); switch (colourNum) { case 1: g.setColor (Color.red); break; } g.fillOval (30, 40, 20, 20); // red light g.fillOval (30, 70, 20, 20); // yello light g.fillOval (30, 100, 20, 20); // green light } public void actionPerformed (ActionEvent evt) { if (evt.getSource () == bttn1) colourNum = 1; else if (evt.getSource () == bttn2) colourNum = 2; else colourNum = 3; repaint (); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload