| | |
Java Swing Tutorial
     JFrame
     JInternalFrame
     JWindow
     JOptionPane
     JLabel
     JTextField
     JPasswordField
     JTextArea
     JButton
     JRadioButton
     JCheckBox
     JComboBox
     Jlist
     JTabbedPane
     JMenuBar
     Scrollable JPopupMenu
     JToolBar
     BorderLayout
     FlowLayout
     GridLayout
     GridBagLayout
     Java Look and Feel
     Swing Calculator
     Swing Address book
     Shuffle Game
     Beginner Java Tutorial
     JDBC Tutorial
     Java Interview Questions
     



Java JButton class example

JButton

Java Swing Tutorial Explaining the JButton Component. The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including JButton. A button is a component the user clicks to trigger a specific action.




There are several types of buttons in Java, all are subclasses of AbstractButton.

  • command buttons: is created with class JButton. It generates ActionEvent.
  • toggle buttons: have on/off or true/false values.
  • check boxes: a group of buttons. It generates ItemEvent.
  • radio buttons: a group of buttons in which only one can be selected. It generates ItemEvent.

    JButton Source Code

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.net.URL;
    import javax.swing.AbstractButton;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class JButtonDemo extends JPanel implements ActionListener {
    
    	protected static JButton jbnLeft, jbnMiddle, jbnRight;
    	public JButtonDemo() {
    		// Create Icons that can be used with the jButtons
    		ImageIcon leftButtonIcon = createImageIcon("rightarrow.JPG");
    		ImageIcon middleButtonIcon = createImageIcon("java-swing-tutorial.JPG");
    		ImageIcon rightButtonIcon = createImageIcon("leftarrow.JPG");
    		jbnLeft = new JButton("Disable centre button", leftButtonIcon);
    		jbnLeft.setVerticalTextPosition(AbstractButton.CENTER);
    		jbnLeft.setHorizontalTextPosition(AbstractButton.LEADING);
    		jbnLeft.setMnemonic(KeyEvent.VK_D);
    		// Alt-D clicks the button
    		jbnLeft.setActionCommand("disable");
    		jbnLeft.setToolTipText("disable the Centre button."); // Adding Tool
    									// tips
    		jbnMiddle = new JButton("Centre button", middleButtonIcon);
    		jbnMiddle.setVerticalTextPosition(AbstractButton.BOTTOM);
    		jbnMiddle.setHorizontalTextPosition(AbstractButton.CENTER);
    		jbnMiddle.setMnemonic(KeyEvent.VK_M);
    		// Alt-M clicks the button
    		jbnMiddle.setToolTipText("Centre button");
    		jbnRight = new JButton("Enable centre button", rightButtonIcon);
    		// Use the default text position of CENTER, TRAILING (RIGHT).
    		jbnRight.setMnemonic(KeyEvent.VK_E);
    		// Alt-E clicks the button
    		jbnRight.setActionCommand("enable");
    		jbnRight.setEnabled(false);
    		// Disable the Button at creation time
    		// Listen for actions on Left and Roght Buttons
    		jbnLeft.addActionListener(this);
    		jbnRight.addActionListener(this);
    		jbnRight.setToolTipText("Enable the Centre button.");
    		// Add Components to the frame, using the default FlowLayout.
    		add(jbnLeft);
    		add(jbnMiddle);
    		add(jbnRight);
    	}
    	public void actionPerformed(ActionEvent e) {
    		if ("disable".equals(e.getActionCommand())) {
    			jbnMiddle.setEnabled(false);
    			jbnLeft.setEnabled(false);
    			jbnRight.setEnabled(true);
    		} else {
    			jbnMiddle.setEnabled(true);
    			jbnLeft.setEnabled(true);
    			jbnRight.setEnabled(false);
    		}
    	}
    	// Returns an ImageIcon, or null if the path was invalid.
    	protected static ImageIcon createImageIcon(String path) {
    		URL imgURL = JButtonDemo.class.getResource(path);
    		if (imgURL != null) {
    			return new ImageIcon(imgURL);
    		} else {
    			System.err.println("Couldn't find image in system: " + path);
    			return null;
    		}
    	}
    	// Create the GUI and show it.
    	private static void createGUI() {
    		JFrame.setDefaultLookAndFeelDecorated(true);
    		// Create and set up the frame.
    		JFrame frame = new JFrame("jButton usage demo");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		// Create and set up the content pane.
    		JButtonDemo buttonContentPane = new JButtonDemo();
    		buttonContentPane.setOpaque(true); // content panes must be opaque
    		frame.getRootPane().setDefaultButton(jbnLeft);
    		frame.setContentPane(buttonContentPane);
    		// Display the window.
    		frame.pack();
    		frame.setVisible(true);
    	}
    	public static void main(String[] args) {
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    
    			public void run() {
    				createGUI();
    			}
    		});
    	}
    }
    

    Output

    Download  jButton Source Code

    Another Example: JButton Source Code


     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class JButtonDemo2 {
    
    	JFrame jtfMainFrame;
    	JButton jbnButton1, jbnButton2;
    	JTextField jtfInput;
    	JPanel jplPanel;
    	public JButtonDemo2() {
    		jtfMainFrame = new JFrame("Which Button Demo");
    		jtfMainFrame.setSize(50, 50);
    		jbnButton1 = new JButton("Button 1");
    		jbnButton2 = new JButton("Button 2");
    		jtfInput = new JTextField(20);
    		jplPanel = new JPanel();
    		jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys
    		jbnButton1.addActionListener(new ActionListener() {
    
    			public void actionPerformed(ActionEvent e) {
    				jtfInput.setText("Button 1!");
    			}
    		});
    		jbnButton2.setMnemonic(KeyEvent.VK_I);
    		jbnButton2.addActionListener(new ActionListener() {
    
    			public void actionPerformed(ActionEvent e) {
    				jtfInput.setText("Button 2!");
    			}
    		});
    		jplPanel.setLayout(new FlowLayout());
    		jplPanel.add(jtfInput);
    		jplPanel.add(jbnButton1);
    		jplPanel.add(jbnButton2);
    		jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER);
    		jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		jtfMainFrame.pack();
    		jtfMainFrame.setVisible(true);
    	}
    	public static void main(String[] args) {
    		// Set the look and feel to Java Swing Look
    		try {
    			UIManager.setLookAndFeel(UIManager
    					.getCrossPlatformLookAndFeelClassName());
    		} catch (Exception e) {
    		}
    		JButtonDemo2 application = new JButtonDemo2();
    	}
    }

     

    Output

    Download  jButton Source Code

    Java JButton Hierarchy

    javax.swing
    Class JButton
    java.lang.Object
    java.awt.Component
    java.awt.Container
    javax.swing.JComponent
    javax.swing.AbstractButton
    javax.swing.JButton
    All Implemented Interfaces:
    Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable, SwingConstants
    Direct Known Subclasses:
    BasicArrowButton, MetalComboBoxButton

    JButton Constructor

    JButton()
    Creates a button with no set text or icon.

    JButton(Action a)
    Creates a button where properties are taken from the Action supplied.

    JButton(Icon icon)
    Creates a button with an icon.

    JButton(String text)
    Creates a button with text.

    JButton(String text, Icon icon)
    Creates a button with initial text and an icon.

  •  
     
        Java is a trademark of Sun Microsystems, Inc.
    | | |
    © Copyright 2007-08 javabeginner.com