package edu.hawaii.ics.yucheng; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.Timer; /** * A status label. */ @SuppressWarnings("serial") class StatusLabel extends JLabel { /** * A simple class that resets the text when the timer expires. */ class Delegate implements ActionListener { /** * Executes when the timer expires. Resets the text. * * @param arg0 The argument (not used) */ public void actionPerformed(final ActionEvent arg0) { resetText(); } } private String myDefaultText; private final Timer myTimer; /** * Initializes a new instance of the class. * * @param text The initial text in the label. */ public StatusLabel(final String text) { super(text); // Create a timer and listen for events. When the timer expires, myTimer = new Timer(0, new Delegate()); // Do not repeat the timer. myTimer.setRepeats(false); } /** * Resets the text in the status label. */ public void resetText() { if (myDefaultText != null) setText(myDefaultText); } /** * Sets the text that appears when the text is reset or the timer expires. * * @param text The text. */ public void setDefaultText(final String text) { myDefaultText = text; } /** * Sets the text in the label. * * @param text The text. */ @Override public void setText(final String text) { assert null != text; super.setText(text); // Stop the timer if it is running. It's possible that it is null since // the super's constructor calls this method. if (myTimer != null) myTimer.stop(); } /** * Sets the text in the label with a specified timeout. After the timeout, the * default test is displayed. * * @param text The text. * * @param timeout The timeout in milliseconds. */ public void setText(final String text, final int timeout) { assert null != text; assert null != myTimer; assert timeout >= 0; // Set the text and start or restart the timer. setText(text); myTimer.setInitialDelay(timeout); myTimer.restart(); } }