Presentation is loading. Please wait.

Presentation is loading. Please wait.

JButton Chapter 11 Lecture 3.

Similar presentations


Presentation on theme: "JButton Chapter 11 Lecture 3."— Presentation transcript:

1 JButton Chapter 11 Lecture 3

2 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

3 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

4 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

5 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.

6 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;

7 Button variables declaration
private JButton plainJButton; // button with just text private JButton fancyJButton; // button with icons

8 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

9 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 );

10 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


Download ppt "JButton Chapter 11 Lecture 3."

Similar presentations


Ads by Google