Source of IconDemo.java


  1: import javax.swing.ImageIcon;
  2: import javax.swing.JButton;
  3: import javax.swing.JFrame;
  4: import javax.swing.JLabel;
  5: import javax.swing.JPanel;
  6: import javax.swing.JTextField;
  7: import java.awt.Color;
  8: import java.awt.Container;
  9: import java.awt.BorderLayout;
 10: import java.awt.FlowLayout;
 11: import java.awt.event.ActionEvent;
 12: import java.awt.event.ActionListener;
 13: 
 14: /**
 15:  Simple demonstration of putting icons in buttons and labels.
 16: */
 17: public class IconDemo extends JFrame implements ActionListener
 18: {
 19:     public static final int WIDTH = 400;
 20:     public static final int HEIGHT = 200;
 21:     private JTextField message;
 22: 
 23:     public IconDemo( )
 24:     {
 25:         setSize(WIDTH, HEIGHT);
 26:         addWindowListener(new WindowDestroyer( ));
 27:         setTitle("Icon Demonstration");
 28:         Container content = getContentPane( );
 29:         content.setBackground(Color.WHITE);
 30:         content.setLayout(new BorderLayout( ));
 31: 
 32:         JLabel niceLabel = new JLabel("Nice day!");
 33:         ImageIcon smileyIcon = new ImageIcon("smiley.gif");
 34:         niceLabel.setIcon(smileyIcon);
 35:         content.add(niceLabel, BorderLayout.NORTH);
 36: 
 37:         JPanel buttonPanel = new JPanel( );
 38:         buttonPanel.setLayout(new FlowLayout( ));
 39:         JButton helloButton = new JButton("Hello");
 40:         ImageIcon dukeWavingIcon = new ImageIcon("duke_waving.gif");
 41:         helloButton.setIcon(dukeWavingIcon);
 42:         helloButton.addActionListener(this);
 43:         buttonPanel.add(helloButton);
 44:         JButton byeButton = new JButton("Good bye");
 45:         ImageIcon dukeStandingIcon =
 46:                   new ImageIcon("duke_standing.gif");
 47:         byeButton.setIcon(dukeStandingIcon);
 48:         byeButton.addActionListener(this);
 49:         buttonPanel.add(byeButton);
 50:         content.add(buttonPanel, BorderLayout.SOUTH);
 51: 
 52:         message = new JTextField(30);
 53:         content.add(message, BorderLayout.CENTER);
 54:     }
 55: 
 56:     public void actionPerformed(ActionEvent e)
 57:     {
 58:        if (e.getActionCommand( ).equals("Hello"))
 59:            message.setText("Glad to meet you!");
 60:        else if (e.getActionCommand( ).equals("Good bye"))
 61:            message.setText(
 62:                   "OK, click the upper right button. I'll miss you.");
 63:        else
 64:            System.out.println("Error in button interface.");
 65:     }
 66: 
 67:     /**
 68:      Creates and displays a window of the class IconDemo.
 69:     */
 70:     public static void main(String[] args)
 71:     {
 72:         IconDemo iconGui = new IconDemo( );
 73:         iconGui.setVisible(true);
 74:     }
 75: }