JButton in Swing Example for Beginners

This exhaustive example illustrates creating JButton in Swing. This example also covers all the core methods of javax.swing.JButton class.

import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
import java.awt.event.*;
class JButtonExample extends JFrame
{
JButton b1,b2,b3,b4,b5;
ImageIcon i1,i2,i3;

    public JButtonExample()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("JButton Demo 1");
        setLayout(new FlowLayout());
        setSize(400,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
       
        // Create ImageIcons
        i1=new ImageIcon("soccer.png");
        i2=new ImageIcon("soccersmall.png");
        i3=new ImageIcon("soccerselected.png");
       
        // Create using first
        // default constructor
        b1=new JButton();
       
        // Second constructor
        // Takes javax.swing.Action object
        b2=new JButton(new DefaultEditorKit.BeepAction());
       
        // Third constructor
        // Takes javax.swing.Icon
        // ImageIcon is implementation of interface Icon
        b3=new JButton(i2);
       
        // Fourth constructor
        // Takes String which is
        // text on the JButton
        b4=new JButton("Button 4");
       
        // Fifth constructor
        // Takes String, ImageIcon
        b5=new JButton("Button 5",new ImageIcon("soccersmall.png"));
       
       
        // Set some text to buttons
        b1.setText("Button 1");
        b2.setText("Click me");
       
        // This hides the action text
        // Not mostly used
        // Since if the programmer
        // doesn't want the action text
        // to display, he usually might
        // want some other text to
        // get displayed
        // So he uses setText()
        // If he wants no text,
        // Then he calls, setText("");
       
        // b2.setHideActionText(true);
       
        // Get text on each button
        System.out.println("Text on b1 is "+b1.getText());
        System.out.println("Text on b2 is "+b2.getText());
        System.out.println("Text on b3 is "+b3.getText());
        System.out.println("Text on b4 is "+b4.getText());
        System.out.println("Text on b5 is "+b5.getText());
       
        //  Set b1 as default button
        b1.setDefaultCapable(true);
       
        // isDefaultCapable()
        System.out.println("Is b1 default? "+b1.isDefaultCapable());
       
        // Set content ar4ea filled false
        // Just see the effect
        b3.setContentAreaFilled(false);
       
        // Do not paint focus for b3
        // This removes the border
        // around the text and icon
        // (if present).
        // By default it is true
        b1.setFocusPainted(false);
        b2.setFocusPainted(false);
        b3.setFocusPainted(false);
        b4.setFocusPainted(false);
       
        // Do not paint border for b3
        // This removes border
        // By default it is true
        b2.setBorderPainted(false);
        b3.setBorderPainted(false);
       
        // Using isBorderPainted()
        // Checks whether the border
        // is painted on the JButton
        // on which it is called
        System.out.println("Button 1 border painted? "+b1.isBorderPainted());
        System.out.println("Button 2 border painted? "+b2.isBorderPainted());
        System.out.println("Button 3 border painted? "+b3.isBorderPainted());
        System.out.println("Button 4 border painted? "+b4.isBorderPainted());
        System.out.println("Button 5 border painted? "+b5.isBorderPainted());
       
        // Using isFocusPainted()
        // Checks whether the focus
        // is painted on the JButton
        // on which it is called
        System.out.println("Button 1 focus painted? "+b1.isFocusPainted());
        System.out.println("Button 2 focus painted? "+b2.isFocusPainted());
        System.out.println("Button 3 focus painted? "+b3.isFocusPainted());
        System.out.println("Button 4 focus painted? "+b4.isFocusPainted());
        System.out.println("Button 5 focus painted? "+b5.isFocusPainted());
       
        // Disable b5
        // By default every button
        // is enabled
        b5.setEnabled(false);
       
        // Set some disabled icon
        // for b5
        b5.setDisabledIcon(i1);
       
        // Set mnemonics
        // setMnemonic(char) is
        // obselete
        // setMnemonic(int) is
        // used
        // Ascii values
        // 49 - 1
        // 50 - 2....
       
       
        // Whenever uses presses
        // mnemonic with Alt pressed
        // the corresponding button
        // is clicked
        b1.setMnemonic(49);
        b2.setMnemonic(50);
        b3.setMnemonic(51);
        b4.setMnemonic(52);
       
        // Set displayed mnemonic index
        // The index in the text of
        // the button is underlined
        // By default, the mnemonic itself
        // is underlined, if the mnemonic
        // is not in the text, then nothing
        // is underlined i.e. the displayed
        // mnemonic index is -1
        // If no mnemonic is set, -1 is
        // the displayed mnemonic index
       
        // If the index does not exist
        // IllegalArgumentException is thrown
        b2.setDisplayedMnemonicIndex(1);
       
        // Get displayed mnemonic indices
        System.out.println("Displayed mnemonic index for b1 "+b1.getDisplayedMnemonicIndex());
        System.out.println("Displayed mnemonic index for b2 "+b2.getDisplayedMnemonicIndex());
        System.out.println("Displayed mnemonic index for b3 "+b3.getDisplayedMnemonicIndex());
        System.out.println("Displayed mnemonic index for b4 "+b4.getDisplayedMnemonicIndex());
        System.out.println("Displayed mnemonic index for b5 "+b5.getDisplayedMnemonicIndex());
       

        // Set the multi click threshold
        // After the user presses on the
        // mouse button, the ActionEvent
        // is fired. From the next mouse
        // press onwards, if the user
        // continuously presses the mouse
        // between a gap less than 1000
        // milliseconds (here), then the
        // ActionEvent is not fired.
        // However, if the delay between
        // each mouse press is greater
        // than 1000 milliseconds, the
        // ActionEvent is generated
        b2.setMultiClickThreshhold(1000);
       
        // Get multi click threshold
        System.out.println("Multi click threshold for b1 "+b1.getMultiClickThreshhold());
        System.out.println("Multi click threshold for b2 "+b2.getMultiClickThreshhold());
        System.out.println("Multi click threshold for b3 "+b3.getMultiClickThreshhold());
        System.out.println("Multi click threshold for b4 "+b4.getMultiClickThreshhold());
        System.out.println("Multi click threshold for b5 "+b5.getMultiClickThreshhold());

        // Set some rollover icon
        // This icon is set to the button
        // when mouse is hovered on it
        b3.setRolloverIcon(i1);
       
        // Set roll over disabled
        // You'll not find any
        // affect such as thickening
        // of border around the button.
        // The affect that comes
        // when the mouse is hover
        // on the button does not
        // appear.
       
        // If there is a roll over
        // icon, that will not
        // appear
        b1.setRolloverEnabled(false);
       
        // Print is Roll over enabled
        // Roll over is independent of
        // whether the icon is disabled
        // or enabled.
        System.out.println("Is roll over enabled for b1 "+b1.isRolloverEnabled());
        System.out.println("Is roll over enabled for b2 "+b2.isRolloverEnabled());
        System.out.println("Is roll over enabled for b3 "+b3.isRolloverEnabled());
        System.out.println("Is roll over enabled for b4 "+b4.isRolloverEnabled());
        System.out.println("Is roll over enabled for b5 "+b5.isRolloverEnabled());
       
        // Arm the JButton b1
        ButtonModel model1=b1.getModel();
        model1.setArmed(true);

        // Print is armed
        System.out.println("Is b1 armed ? "+model1.isArmed());
       
       
        // Select the button b2
        b2.setSelected(true);
       
        // Register ActionListener
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                System.out.println("hai");
            }
        });
       
        // Register some actions
        // Using AbstractAction could be
        // better, because the AbstractAction
        // is an implementation of Action interface
        // If Action interface is to be implemented
        // Then every method in it should be
        // implemented.
        // As only actionPerformed(ActionEvent) is
        // needed, AbstractAction is used.
        AbstractAction a=new AbstractAction(){
            public void actionPerformed(ActionEvent ae)
            {
                // ActionEvent here is generated
                // only when a JButton is clicked
                // since there is no other component
                // other than a JButton
                setTitle("You clicked "+ae.getActionCommand());
            }
        };
       
        // Now the icon won't be displayed
        b3.setAction(a);
       
        // Now the text won't be displayed
        b4.setAction(a);
       
        // Set some action commands
        // These commands are a way of
        // detecting the event source
        // when the handler is written
        // only once and when the getSource()
        // method is used.
        // Every button is set a unique action
        // command, and to know which button
        // is pressed, the action command can
        // be used.
       
        // One alternative technique is directly
        // using the text on the button, provided
        // that other buttons to which the same
        // ActionListener is registered don't have
        // the same text on them.
        // As this raises as a confusing issue,
        // action commands would be more
        // appropriate in such situations
       
        // Rember to set ActionCommands
        // after the setAction() method
        // The action must be set before
        // the action command is.
        // Otherwise, the action commands
        // are not set.
        b3.setActionCommand("Button 3");
        b4.setActionCommand("Button 4");
       
        // Set the icon again!
        b3.setIcon(i2);
       
        // Set the text again!
        b4.setText("Button 4");
       
        // Set some background
        b1.setBackground(Color.GRAY);
       
        // Set some foreground
        b1.setForeground(Color.white);
       
        // Add the buttons
        add(b1);
        add(b2);
        add(b3);
        add(b4);
        add(b5);
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new JButtonExample();
            }
        });
    }
}

Also see using JButton to minimize/maximize/close JFrame

Screenshot of JButton Example

No comments: