JButton Chapter 11 Lecture 3
Jbutton A button is a component the user clicks to trigger a specific action. Types of buttons include: Command buttons Checkboxes Toggle buttons Radio buttons
Swing button hierarchy JComponent AbstractButton JButton JToggleButton All the button types are subclassese of AbstractButton (javax.swing) --- declares the common features of Swing buttons JCheckBox JRadioButton
JButton A command button generates an ActionEvent when the user clicks the button. Command buttons are created with class Jbutton. The text on the face of a Jbuttonis called a button label. A GUI can have many JButtons Button label should be UNIQUE in the currently displayed GUI
Constructor Summary 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.
Example – ButtonFrame.java import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane;
Button variables declaration private JButton plainJButton; // button with just text private JButton fancyJButton; // button with icons
Creates buttons plainJButton = new JButton( "Plain Button" ); // button with text add( plainJButton ); // add plainJButton to Jframe ----------------------------------------------------- fancyJButton = new JButton( "Fancy Button", bug1 ); // set image fancyJButton.setRolloverIcon( bug2 ); // set rollover image add( fancyJButton ); // add fancyJButton to JFrame Rollover : The icon is displayed when the user positions the mouse over the button setRolloverIcon is inherited from the AbstractButton
Example - continued Create an object of private inner class ButtonHandler and register it as event handler for each button: ButtonHandler handler = new ButtonHandler(); fancyJButton.addActionListener( handler ); plainJButton.addActionListener( handler );
Class ButtonHandler // inner class for button event handling private class ButtonHandler implements ActionListener { // handle button event public void actionPerformed( ActionEvent event ) JOptionPane.showMessageDialog( ButtonFrame.this, String.format( "You pressed: %s", event.getActionCommand() ) ); } // end method actionPerformed } // end private inner class ButtonHandler