import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MoodDisplay extends JFrame
{
// JLabel can display text and images
private JLabel msgLabel, iconLabel;
private JButton nextButton;
private int current;
private Icon bug, tiger, toucan;
public MoodDisplay()
{
super("How are you feeling?");
Container container = getContentPane();
container.setLayout(new FlowLayout());
msgLabel = new JLabel("Does this represent you
today?");
container.add(msgLabel);
// load icons for label, just do this once
bug = new ImageIcon("bug1.gif");
tiger = new ImageIcon("tiger.jpg");
toucan = new ImageIcon("toucan.gif");
// load first choice into iconLabel
iconLabel = new
JLabel("Roar",tiger,SwingConstants.CENTER);
iconLabel.setToolTipText("Feeling like a tiger");
container.add(iconLabel);
// Load button with button title
nextButton = new JButton("Change mood");
nextButton.setEnabled(true); // user can press it
nextButton.setMnemonic('c'); // alt-c is mnemonic
nextButton.setToolTipText("Turn me into someone
else"); // button tooltip
nextButton.addActionListener(new NextListener()); //
action listener below
current = 0; // keeps track of which mood is
displayed
container.setBackground(Color.blue);
container.add(nextButton);
setSize(500,400);
setVisible(true);
}
public static void main(String[] args)
{
MoodDisplay application = new MoodDisplay();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Inner class for button listener
private class NextListener implements ActionListener
{
// ActionListener interface requires this
method
public void actionPerformed(ActionEvent event)
{
current = (current + 1) % 3;
iconLabel.setIconTextGap(3); // optional gap in
pixels
if (current == 0)
{
iconLabel.setIcon(tiger);
// Three options for vertical text
position are CENTER, TOP, BOTTOM
// Horizontal text positions (not used
here) are LEADING, LEFT,
// CENTER, RIGHT AND TRAILING
iconLabel.setVerticalTextPosition(SwingConstants.CENTER);
iconLabel.setToolTipText("Feeling like a
tiger");
iconLabel.setText("Roar");
}
else if (current == 1)
{
iconLabel.setIcon(toucan);
iconLabel.setVerticalTextPosition(SwingConstants.TOP);
iconLabel.setToolTipText("Fruit Loops
anyone?");
iconLabel.setText("Flying");
}
else
{
iconLabel.setIcon(bug);
iconLabel.setText("Down to
Earth");
iconLabel.setToolTipText("This really bugs me");
iconLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
}
// repaint causes label to redisplay
repaint();
}
}
}