Favorite Color
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ExerciseText
{
public static void main(String [] args)
{
MyFrame frame = new MyFrame("Favorite Color");
frame.pack();
frame.setLocation(100, 75);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class MyFrame extends JFrame
{
JLabel favorite = new JLabel("Enter your favorite color:");
JTextField text = new JTextField(20);
public MyFrame(String s)
{
super(s);
setLayout(new FlowLayout());
add(favorite);
add(text);
text.addActionListener(new FavHandler()); // attach handler to text field
}
class FavHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String s = text.getText();
String response = s + " is nice";
text.setText(response);
}
}
}
|