Edit the below code to allow it to run as a Java Applet. Program should display
ID: 3681009 • Letter: E
Question
Edit the below code to allow it to run as a Java Applet. Program should display a button that when clicked cycles through yellow and dark gray.
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Training extends JApplet
{
private Container contentHolder;
public void start()
{
contentHolder=getContentPane();
contentHolder.setBackgound(Color.white);
final JButton jbt1=new JButton ("On/Off");
final JButton jbt2=new JButton ("On/Off");
jbt2.setVisible(false);
contentHolder.setLayout(new FlowLayout());
contentHolder.add(jbt1);
contentHolder.add(jbt2);
jbt1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
contentHolder.setBackground(Color.darkGray);
jbt1.setVisible(false);
jbt2.setVisible(true);
}
});
jbt2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
contentHolder.setBackground(Color.yellow);
jbt1.setVisible(true);
jbt2.setVisible(false);
}
});
}
}
Explanation / Answer
Hi, Please find the updated (highlighed) code to allow it to run as a Java Applet.
Training.java
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
<applet code = "Training.class" width = "400" height="400"></applet>
*/
public class Training extends JApplet
{
private Container contentHolder;
public void start()
{
contentHolder=getContentPane();
contentHolder.setBackground(Color.white);
final JButton jbt1=new JButton ("On/Off");
final JButton jbt2=new JButton ("On/Off");
jbt2.setVisible(false);
contentHolder.setLayout(new FlowLayout());
contentHolder.add(jbt1);
contentHolder.add(jbt2);
jbt1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
contentHolder.setBackground(Color.darkGray);
jbt1.setVisible(false);
jbt2.setVisible(true);
}
});
jbt2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
contentHolder.setBackground(Color.yellow);
jbt1.setVisible(true);
jbt2.setVisible(false);
}
});
}
}
How to Execute:
> Save the above program into file with the name "Training.java"
> Open cmd prompt and go to the path where Training.java file has been saved.
> complite the java program by using below commands.
>javac Training.java
>appletviewer Training.java
Your applet will open and run. When clicked on button Yellow and Gray colors will appear.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.