Document Sample
Buttons Powered By Docstoc
• A square or rectangular-shaped control with a label inside that
  indicates action to be accomplished.
• The label may be either text, graphics or both
• Purpose
     – To start actions
     – To change properties
     – To display a pop-up menu
• Advantages
     – Always visible, reminding of choices available
     – Convenient and logically organized in the work area
     – Larger size generally provides faster selection target
     – 3-D appearance can provide visual feedback through button movement
       when activated
     – Allows the use of mnemonics
     – Faster than using a menu selection sequence
12/01/06                      JHU/APL EN 605.482                            1
                               More on Buttons
• Disadvantages
     –     Consumes screen space
     –     Size limits the number that may be displayed
     –     Requires looking away from the main working area to activate
     –     Requires moving the pointer to select
• Labeling guidelines
     –     Provide meaningful descriptions of the actions that will be performed
     –     Display labels in regular system font, in the same size font
     –     Provide consistency in button labeling across all screens
     –     Never reduce the font size of some labels to create equal sized buttons
• Restrict the number of buttons on a window to six or fewer

12/01/06                           JHU/APL EN 605.482                                2
                            Button locations
• Exiting the dialog
     – Positioned centered and aligned horizontally at the bottom
• Invoking a dialog feature or expanding the dialog
     – Position centered and aligned vertically on the right side
• Provide equal and adequate spacing between adjacent buttons
• Provide adequate spacing between buttons and the screen body

12/01/06                        JHU/APL EN 605.482                  3
                       Button Intent Indicators
• When a button causes an action to be immediately performed:
     – No Intent indicator is necessary
• When a button leads to a dialog or other pop-up window
     – Include an ellipsis (…) after the label
• When a button leads to a menu
     – Include a pointing triangle or “>”
• When a button leads to an expanding dialog:
     – Include a double arrow “>>”
     – When dialog expands, disable expansion button
     – Place contraction button beneath or to the right of the expansion button

12/01/06                        JHU/APL EN 605.482                                4
                         More on Buttons
• When a window is first displayed, provide a default action, if practical
• If the action is positive (a confirmation or application of an activity)
  then it is a good candidate for the default
• If a destructive action is performed, the default should be CANCEL
• Temporarily unavailable choices should be dimmed or “grayed out”,
  they should not be removed
• Assign a keyboard mnemonic to each button to facilitate keyboard
• Maintain the same mnemonic on all identical buttons on other screens
• If a window can be scrolled…do not scroll the buttons
• Highlight a button in some visually distinctive manner when the
  pointer is resting on it and the button is available for selection,
  likewise show that the button is being pressed in some way.

12/01/06                     JHU/APL EN 605.482                          5
                  Buttons in Java
JComponent   AbstractButton           JButton

                                   JToggleButton   JCheckBox


12/01/06             JHU/APL EN 605.482                     6
• Defines the common behaviors for the JButton, JToggleButton,
  JCheckbox, and the JRadioButton classes.
• Many methods, but most are set/get pairs for the following
     –     Icon
     –     PressedIcon
     –     SelectedIcon
     –     RolloverIcon
     –     RolloverSelectedIcon
     –     DisabledIcon
     –     DisabledSelectedIcon
     –     VerticalAlignment
     –     HorizontalAlignment
     –     VerticalTextPosition
     –     HorizontalTextPosition

12/01/06                            JHU/APL EN 605.482           7
• Constructors
     JButton(Icon icon)
     JButton(String text)
     JButton(String text, Icon icon)
     JButton(Action action)
• Like JLabel, JButton now supports html text as a string. This allows
  for multiple fonts, colors, etc in the Button
• JButton has few methods of its own, some significant ones are:
     boolean isDefaultButton()
     boolean isDefaultCapable()
     void setDefaultCapable(boolean defaultCapable)

12/01/06                    JHU/APL EN 605.482                           8
                             Button Events
• Buttons are the first example of JComponent designed for user input
• Need to handle events from the buttons
• Three types of event generated
     – Action (button clicked: pushed and released)
     – Item (from pushes and releases both)
     – Change (from pushes and releases both)
• Most often used listener is the ActionListener
     – Mouse clicks
     – Focus + Space_Bar
• Three ways of handling event listeners
     – Separate Class
     – Handled within object (implements ActionListener)
     – Inner Class

12/01/06                       JHU/APL EN 605.482                       9
                     Adding Icons to Buttons
•   Unlike the original AWT, it is now
    easy to add graphics to buttons
•   Gif, Animated Gif, and JPEG
    formats supported
•   Buttons may respond to mouse
•   Focus of buttons may be painted or
•   Code Example

12/01/06                       JHU/APL EN 605.482   10
                      Other JButton functionality
• Disabling buttons
     – button.setEnabled(boolean);
     – disables events from button
• Adding keyboard mnemonics
• Controlling how a button is painted
     –     setFocusPainted()
     –     Change the icons based on selection, focus, rollover
     –     setBorderPainted()
     –     setContentAreaFilled() transparency of the non-icon area of the button

12/01/06                           JHU/APL EN 605.482                               11
                        Keyboard Mnemonics
• Mnemonics allow applications to support mouseless operation.
• Any JComponent may have a keyboard mnemonic assigned to it
• General rules for mnemonics
     – Use the first letter unless another letter provides a better association
     – Use a distinctive consonant
     – Use a vowel
• Note that in Java, the first occurrence of the letter chosen above, will
  be underlined in the JComponent text
• To add a keyboard mnemonic “S”, use button.setMnemonic(‘S’)
• To call from keyboard use Alt-S
• In JDK1.4+ there is a setDisplayedMnemonicIndex() method to
  control which occurance of the mnemonic is used. This is a new
  AbstractButton method, so it applies to buttons and menus.

12/01/06                         JHU/APL EN 605.482                               12
                   Setting as Default button
• Most GUIs use the notion of a default button, i.e. the equivalent of
  hitting the Enter key without mousing the window. This is called the
  default button.
• Swing provides the ability to define a default button in a JDialog,
  JFrame or JApplet.
• JRootPane has a method setDefaultButton(). This selects the default
  key even if it does not presently have the focus. This means that if you
  have a default key, and VK_ENTER is pressed, that button is
  activated, even if it does not have the focus.

12/01/06                     JHU/APL EN 605.482                         13
                       JButton and properties
• When a button is pushed, it generates an event, which in turn contains
  a reference to the button object it came from.
• How do you tie additional state information to the Button?
     – Subclass the JButton
     – Use JComponent Properties
     – Use an Action
• For example, if you are using a button to set a drawing color
     – button.putClientProperty(“color”,
• Then you can use the getClientProperty() to retrieve it

12/01/06                       JHU/APL EN 605.482                      14
• Allows a programmer to bundle a commonly used procedure and its
  bound properties (such as a name and an image) into a single class
• May be used by
     –     Buttons
     –     Menus
     –     Toolbars
     –     Pop-up menus
• Alternative to writing individual actionPerformed methods throughout
  the code
• If you need to store other information associated with the action in a
  location, where could you store it
     – Source object is a candidate (putClientProperty())
     – But what if there is more than one source?
            • Toolbar, menu, key accelerator, pop-up menu

12/01/06                           JHU/APL EN 605.482                  15
                             Action Interface
     public interface Action extends ActionListener {
           public Object getValue(String key);
           public void putValue(String key, Object value);
           public void setEnabled(boolean b);
           public boolean isEnabled();
           public void addPropertyChangeListener(PropertyChangeListener listener);
           public void removePropertyChangeListener(PropertyChangeListener

12/01/06                         JHU/APL EN 605.482                              16
                      Actions for Buttons
• New for AbstractButton class in JDK 1.3+
• Actions were used in Menus, Toolbars and Popup Menus in JDK1.2,
  but Buttons weren’t included.
• Swing provides an implementation of the Command pattern which
  helps application developer centralize functionality which can be
  accessed from multiple places in the GUI.
• The Action interface is used to provide a stateful ActionListener which
  can provide the implementation of functionality accessed for example
  from the toolbar, a menu item, and a keyboard binding.
• As the state of the Action changes, for instance when it becomes
  disabled, the associated controls change their state accordingly (they
  also become disabled).

12/01/06                    JHU/APL EN 605.482                         17
• Abstract action is…an abstract class implementing the Action
• Only abstract method within the class is the actionPerformed() method
• Used like other “adapter” classes (e.g. MouseAdapter)
• Constructors
           public AbstractAction();
           public AbstractAction(String name);
           public AbstractAction(String name, Icon icon);
• Allows you to register your AbstractAction class with multiple
• Maintain state information within the class
• putProperty methods store String and Icon which is used by other

12/01/06                           JHU/APL EN 605.482                18
                        More on Action interface
• Note the putValue, getValue methods allow you to store any
  information within the AbstractAction
• Action already has a set of well-known keys used by other classes
     –     DEFAULT
     –     NAME: used in menus and buttons
     –     SHORT_DESCRIPTION: automatically sets tooltip text in toolbar
     –     SMALL_ICON: icon used in toolbars
     –     MNEMONIC_KEY: key to use for a mnemonic (new in 1.3)
            • Note: Key must be an Integer Object, use new KeyEvent.VK_A for the a key
     – ACCELERATOR_KEY: key to use for accelerator (new in 1.3)
• NAME and SMALL_ICON are presently used to generate Icons and
  Strings for menus etc...
• If you want to change the displayed name of an action, use:
     action.putValue(Action.NAME, “new name”)
12/01/06                           JHU/APL EN 605.482                                19
                   Sample Custom Action
public class UpAction extends AbstractAction {
   public UpAction() {
    putValue(NAME, “Channel Up”);
    putValue(SMALL_ICON, new ImageIcon(“images/up.gif”);
    putValue(SHORT_DESCRIPTION, “Increment the Channel Number”)
    putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_U));

 12/01/06                 JHU/APL EN 605.482                  20
           Code Example,

12/01/06             JHU/APL EN 605.482      21
• Locks down/up on press as opposed to immediate release as with a
• Parent for JCheckBox and JRadioButton
• Often used in conjunction with ButtonGroup
     – Allows classic radio-button type behavior
     – Only one button in group is selected at a time
• According to Sun, modern GUI design frowns on this particular type of
• Constructors
     JToggleButton(Icon icon)
     JToggleButton(Icon icon, boolean isSelected)
     JToggleButton(String text)
     JToggleButton(String text, Icon icon)
     JToggleButton(String text, boolean isSelected)
     JToggleButton(String text, Icon icon, boolean isSelected)

12/01/06                        JHU/APL EN 605.482                   22

12/01/06          JHU/APL EN 605.482   23
                               Check Boxes
• Used to set one or more options as either on or off
• Two part control consisting of
     – A square box
     – Choice text
• Each option acts as a switch and can be either on or off. When on, a
  mark such as an “X” or “check” appears within the box, or the box is
• Advantages
     – Easy to access choices
     – Easy to compare choices
     – preferred by users
• Disadvantages
     – Consumes screen space
     – Limited number of choices
     – Single check boxes difficult to align with other screen controls
12/01/06                        JHU/APL EN 605.482                        24
                            More on Check Boxes
• Proper usage
     –     For setting attributes, properties, or values
     –     For nonexclusive choices
     –     Where adequate screen space is available
     –     Most useful for Data and choices that are
             • Discrete
             • Small and fixed in number
             • Not easily remembered
             • In need of a textual description to describe meaningfully
             • Most easily understood when the alternatives may be seen together and
               compared to one another
             • Never change in content
• Show a maximum of eight in a grouping
• Enclose the boxes in a border to visually strengthen the relationship
  they possess
• Assign keyboard mnemonics to each check box
12/01/06                             JHU/APL EN 605.482                                25
• Use sentence-style capitalization.
• Write the label as a phrase, not a sentence
• Use no ending punctuation
• If you want to use graphics: Consider toolbars or command buttons
• Avoid repeating words within a grouping
     – Makes it harder for the user to scan for significant labels
• If you need to use an option button with a label, end the label with a

12/01/06                         JHU/APL EN 605.482                        26
                           Check Boxes in Java
• JCheckBox extends JToggleButton to provide a standard check box
• Two states, checked and unchecked
• checkbox.isSelected() returns boolean
• checkbox.setSelected(boolean) selects
• Good use of BoxLayout (and Box class)
     – You would assume GridLayout might be good, but on some platforms it
       horizontally centers each checkbox instead of left justifying
           • This at least occurs on Solaris, but not on Windows
• Same combination of text, icon and selected constructor combinations
  as JToggleButton

12/01/06                           JHU/APL EN 605.482                        27
           Radio Buttons (a.k.a. Option Buttons)
• Set of buttons to set one of a small set of mutually exclusive options,
  preferably less than eight
     – Two recent studies found radio buttons a preferred and very effective
       control for presenting mutually exclusive choices (even up to 30 choices!)
• A two-part control consisting of the following:
     – Small circles, diamonds, or rectangles
     – Choice descriptions
• Advantages
     – Easy to access choices
     – Easy to compare choices
     – Preferred by users
• Disadvantages
     – Consume screen space
     – Limited number of choices

12/01/06                        JHU/APL EN 605.482                             28
                 Proper usage of Radio Buttons
• Used for setting attributes, properties, or values
• Used when adequate screen space is available
• Most useful for data and choices that are:
     – Discrete
     – Small and fixed in number
     – Not easily remembered
     – In need of a textual description to meaningfully describe the alternatives
     – Most easily understood when the alternatives may be seen together and
       compared to one another
     – Never change in content
• Do not use:
• For commands
• Singly, to indicate the presence or absence of a state
     – Use Toggle Button instead

12/01/06                        JHU/APL EN 605.482                                  29
                       More on Radio Buttons
• If the number of choices exceeds eight, consider using a list box or a
  drop-down list box (combo box).
• Always display a default when possible
     – Sometimes this is not desirable (Male/Female selection)
• Preferred orientation of radio buttons is columnar. This aids visual
  scanning and choice comparison
• Arrange selection in expected orders or follow other patterns such as
  frequency of occurrence, sequence of use, or importance
• Captions
     – Provide a caption for each radio button control
     – With a border, display the caption upper-left-justified, or to the left of the
       topmost choice description
     – If the choices are horizontal, use a border or place the caption to the left of
       the choice
• Provide a keyboard mnemonic to each choice description
12/01/06                         JHU/APL EN 605.482                                30
           Organization of Radio Buttons




12/01/06            JHU/APL EN 605.482          31
                    Radio Buttons in Java
• JRadioButton extends JToggleButton also, and provides for a set of
  mutually exclusive selections
• These look very similar to JCheckBoxes, although the have circles
  instead of square “boxes”
• Good use of BoxLayout (and Box class)
• Same combination of text, icon and selected constructor combinations
  as JToggleButton

12/01/06                   JHU/APL EN 605.482                        32
• Object which manages selection of a group of AbtractButtons
• Once an AbstractButton is added to the group, only one in the group
  can be selected at one time
• Normally used with JRadioButton and JToggleButton
• Only a few methods:
     –     public void add(AbstractButton b)
     –     public Enumeration getElements()
     –     public ButtonModel getSelection()
     –     public void remove(AbstractButton b)
     –     public void setSelected(ButtonModel m, boolean b)

12/01/06                          JHU/APL EN 605.482                    33
                                 Button Events
• Two ways to be notified when the state of either a radio button or a
  checkbox changes.
• ActionEvent
     – Any button generates ActionEvent when pressed
     – Generated only for the button the user actually “clicks” on
     – Doesn’t tell you what state it is in
           • You can use getSelected() method on the source of the event
• JToggelButton and its subclasses generate ItemEvents on every state
     – Use ItemListener interface, which has a single method
           • public void itemStateChanged(ItemEvent event)
     – ItemEvent has three methods
           • public Object getItem() gets the Item the event is associated with
           • public ItemSelectable getItemSelectable() returns container of item
           • public int getStateChange() returns ItemEvent.DESELECTED and
12/01/06                            JHU/APL EN 605.482                             34
       Code Example,

12/01/06             JHU/APL EN 605.482           35
                           Custom Icons
• Images can be added to JLabels and JButtons using the ImageIcon
• ImageIcon implements the javax.swing.Icon interface
     – public   void paintIcon(Component comp, Graphics g,
       int x,   int y)
     – public   int getIconWidth();
     – public   int getIconHeight();
• The getIconWidth and getIconHeight methods are invoked by the host
  component to find out how much space the icon needs to draw itself.
• When component needs to be painted, it calls the paintIcon method,
  passing the Graphics object.
• So instead of just holding an image, a button really has the ability to
  hold any object capable of supporting the Icon interface.

12/01/06                    JHU/APL EN 605.482                         36
                           Vetoable listeners
• When a listener is informed of a change to a constrained property, it
  should not assume that the change has already taken place.
• If this happens, the listener will be notified of the property reverting to
  its old value
• How should you handle this?
    – Assume you have something listening for a Font change
    – Best to have a VetoableChangeEvent poll the listeners, then fire a regular

12/01/06                        JHU/APL EN 605.482                                 37
                     Tri-State Check Box
• All java buttons have two states
• Windows, and some other applications, often have three state
     – Checked
     – Cleared
     – Mixed
• There is no easy way to subclass a JCheckBox to accomplish this
• is one solution

12/01/06                    JHU/APL EN 605.482                      38

Shared By: