Task #1 Create an Applet TrafficApplet.java 2. This class currently has all the
ID: 3602870 • Letter: T
Question
Task #1 Create an Applet
TrafficApplet.java
2. This class currently has all the constants you will need to be able to create your
traffic signal. It doesn’t have anything else . You will need to change the class heading so that it extends JApplet.
Task #2 The Timer Object
1. An applet does not have a constructor or a main method. Instead, it has a method named init that performs the same operations as a constructor. The init method accepts no arguments and has a void return type.
Write an init method.
2. Inside the init method, create a Timer object passing in the TIME_DELAY constant and a new TimerListener
(We will be creating the listener class next).
3. Call the start method with the Timer object to generate action events.
Task #3 The TimerListener Class
1. Write a private inner class called TimerListener which implements ActionListener.
2. Inside this class, write an actionPerformed method. This method will check the status variable to see whether it is currently red, orange, or green. Since we want the lights to cycle as a traffic signal, we need to cycle in the order: green, orange, red, green, orange, red, and so on. Once the status is determined, the status should then be set to the next color in the cycle.
3. Redisplay the graphics components (to be created next) by calling the repaint method.
Task #4 Drawing Graphics
1. draw the traffic signal by overriding the paint method. For all graphics, use the named constants included in the class.
2. Call the method that is being overridden in the parent class.
3. Create a yellow rectangle (solid color) for the traffic signal. The constants X_TRAFFICLIGHT, Y_TRAFFICLIGHT,
TRAFFICLIGHT_WIDTH, and TRAFFICLIGHT_HEIGHT have already been defined for your use.
4. Create round lights of red, orange, and green for the signals. These should be
outlines of these colors. The constants X_LIGHTS, Y_REDLIGHT, Y_GREENLIGHT, Y_ORANGELIGHT, and
LIGHT_DIAMETER, have already been defined for your use. Only one light will be filled in at a time, when the
status indicates that one has been chosen. You will need to check the st determine which light to fill in. Remember, the status is changed only in the actionPerformed method (already defined) where the repaint method is also called.
5. Put the shade hoods above the lights by drawing black arcs above each light. The constants HOOD_START_ANGLE and HOOD_ANGLE_SWEPT have already been defined for your use.
6. Try out your applet. If time permits, create a web page on which you can display your applet
Explanation / Answer
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class BalloonApplet extends Applet implements ActionListener {
private Button grow, shrink, left, right;
private Balloon theBalloon;
public void init() {
grow = new Button("Grow");
add(grow);
grow.addActionListener(this);
shrink = new Button("Shrink");
add(shrink);
shrink.addActionListener(this);
left = new Button("Left");
add(left);
left.addActionListener(this);
right = new Button("Right");
add(right);
right.addActionListener(this);
theBalloon = new Balloon();
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == grow)
theBalloon.grow();
if (event.getSource() == shrink)
theBalloon.shrink();
if (event.getSource() == left)
theBalloon.moveLeft();
if (event.getSource() == right)
theBalloon.moveRight();
repaint();
}
public void paint(Graphics g) {
theBalloon.display(g);
}
}
import java.awt.*;
public class Balloon {
private int diameter;
private int x, y;
public Balloon() {
diameter = 10;
x = 20;
y = 50;
}
public void display(Graphics g) {
g.drawOval(x, y, diameter, diameter);
}
public void moveLeft() {
x -= 10;
}
public void moveRight() {
x += 10;
}
public void grow() {
diameter += 5;
}
public void shrink() {
diameter -= 5;
}
}
import java.io.*;
import java.net.*;
class OneConnection {
Socket sock;
BufferedReader in = null;
DataOutputStream out = null;
OneConnection(Socket sock) throws Exception{
this.sock = sock;
in = new BufferedReader(
new InputStreamReader( sock.getInputStream() ) );
out = new DataOutputStream(sock.getOutputStream());
}
String getRequest() throws Exception {
String s=null;
while ( (s=in.readLine())!=null) {
System.out.println("got: "+s);
}
return s;
}
}
import java.io.*;
import java.net.*;
class OneConnection {
Socket sock;
BufferedReader in = null;
DataOutputStream out = null;
OneConnection(Socket sock) throws Exception{
this.sock = sock;
in = new BufferedReader(
new InputStreamReader( sock.getInputStream() ) );
out = new DataOutputStream(sock.getOutputStream());
}
String getRequest() throws Exception {
String s=null;
while ( (s=in.readLine())!=null) {
System.out.println("got: "+s);
}
return s;
}
}
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;
public class LargerHttpd
{
Selector clientSelector;
public void run( int port, int threads ) throws IOException
{
clientSelector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
InetSocketAddress sa = new InetSocketAddress( InetAddress
.getLoopbackAddress(), port );
ssc.socket().bind( sa );
ssc.register( clientSelector, SelectionKey.OP_ACCEPT );
Executor executor = Executors.newFixedThreadPool( threads );
while ( true ) {
try {
while ( clientSelector.select(100) == 0 );
Set<SelectionKey> readySet = clientSelector.selectedKeys();
for(Iterator<SelectionKey> it=readySet.iterator();
it.hasNext();)
{
final SelectionKey key = it.next();
it.remove();
if ( key.isAcceptable() ) {
acceptClient( ssc );
} else {
key.interestOps( 0 );
executor.execute( new Runnable() {
public void run() {
try {
handleClient( key );
} catch ( IOException e) {
System.out.println(e);
}
}
} );
}
}
} catch ( IOException e ) { System.out.println(e); }
}
}
void acceptClient( ServerSocketChannel ssc ) throws IOException
{
SocketChannel clientSocket = ssc.accept();
clientSocket.configureBlocking(false);
SelectionKey key = clientSocket.register( clientSelector,
SelectionKey.OP_READ );
HttpdConnection client = new HttpdConnection( clientSocket );
key.attach( client );
}
void handleClient( SelectionKey key ) throws IOException
{
HttpdConnection client = (HttpdConnection)key.attachment();
if ( key.isReadable() ) {
client.read( key );
} else {
client.write( key );
}
clientSelector.wakeup();
}
public static void main( String argv[] ) throws IOException {
//new LargerHttpd().run( Integer.parseInt(argv[0]), 3/*threads*/ );
new LargerHttpd().run( 1235, 3/*threads*/ );
}
}
class HttpdConnection
{
static Charset charset = Charset.forName("8859_1");
static Pattern httpGetPattern = Pattern.compile("(?s)GET /?(\S*).*");
SocketChannel clientSocket;
ByteBuffer buff = ByteBuffer.allocateDirect( 64*1024 );
String request;
String response;
FileChannel file;
int filePosition;
HttpdConnection ( SocketChannel clientSocket ) {
this.clientSocket = clientSocket;
}
void read( SelectionKey key ) throws IOException {
if ( request == null && (clientSocket.read( buff ) == -1
|| buff.get( buff.position()-1 ) == ' ' ) )
processRequest( key );
else
key.interestOps( SelectionKey.OP_READ );
}
void processRequest( SelectionKey key ) {
buff.flip();
request = charset.decode( buff ).toString();
Matcher get = httpGetPattern.matcher( request );
if ( get.matches() ) {
request = get.group(1);
if ( request.endsWith("/") || request.equals("") )
request = request + "index.html";
System.out.println( "Request: "+request);
try {
file = new FileInputStream ( request ).getChannel();
} catch ( FileNotFoundException e ) {
response = "404 Object Not Found";
}
} else
response = "400 Bad Request" ;
if ( response != null ) {
buff.clear();
charset.newEncoder().encode(
CharBuffer.wrap( response ), buff, true );
buff.flip();
}
key.interestOps( SelectionKey.OP_WRITE );
}
void write( SelectionKey key ) throws IOException {
if ( response != null ) {
clientSocket.write( buff );
if ( buff.remaining() == 0 )
response = null;
} else if ( file != null ) {
int remaining = (int)file.size()-filePosition;
long sent = file.transferTo( filePosition, remaining,
clientSocket);
if ( sent >= remaining || remaining <= 0 ) {
file.close();
file = null;
} else
filePosition += sent;
}
if ( response == null && file == null ) {
clientSocket.close();
key.cancel();
} else
key.interestOps( SelectionKey.OP_WRITE );
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.