There are three components presented in this window - a JButton, a JCheckBox and a JTextField. All three of these are capable of generating an ActionEvent, and we could setup the program to handle the events coming from any of these three. However, the program descrption indicated that we should evaluate the mood when the user presses the Give Mood button, so the solution below only handles events from that component (however, you could easily add processing of the events from the other two components).
Note that I disabled text field input from the user, since no input is required from the user (i.e. the user can see text in the text field but cannot enter their own text).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExerciseCB
{
public static void main(String [] args)
{
MyFrame frame = new MyFrame("Mood Reader");
frame.pack();
frame.setLocation(100, 75);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class MyFrame extends JFrame
{
JButton mood = new JButton("Give mood");
JTextField text = new JTextField(12);
JCheckBox good = new JCheckBox("good", true);
public MyFrame(String s)
{
super(s);
setLayout(new FlowLayout());
text.setEnabled(false); // disables user input
add(mood);
add(text);
add(good);
mood.addActionListener(new MoodHandler());
}
class MoodHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (good.isSelected())
text.setText("happy");
else
text.setText("sad");
}
}
}
|