The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > JButton  [9 examples]

e746. Adding an Icon to a JButton Component

If the action used to create the button contains an icon, the button will be created using that icon. The icon will appear to the left of the text; to change the icon's position, see e747 Moving the Icon in a JButton Component.
    // Retrieve the icon
    Icon icon = new ImageIcon("icon.gif");
    
    // Create an action with an icon
    Action action = new AbstractAction("Button Label", icon) {
        // This method is called when the button is pressed
        public void actionPerformed(ActionEvent evt) {
            // Perform action
        }
    };
    
    // Create the button; the icon will appear to the left of the label
    JButton button = new JButton(action);
If the action does not have an icon or a different icon must be used, add or change the icon using setIcon():
    // Add or change the icon; it will appear to the left of the text
    button.setIcon(icon);
    
    // Set to null to remove icon
    button.setIcon(null);

 Related Examples
e743. Creating a JButton Component
e744. Changing the Label of a JButton Component
e745. Creating a Multiline Label for a JButton Component
e747. Moving the Icon in a JButton Component
e748. Moving the Label/Icon Pair in a JButton Component
e749. Setting the Gap Size Between the Label and Icon in a JButton Component
e750. Adding a Disabled Icon to a JButton Component
e751. Adding a Rollover and Pressed Icon to a JButton Component

See also: Actions    JCheckBox    JComboBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Keystrokes and Input Maps    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.