Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 12 (The basics) Menus, Toolbars, and Actions. Easy for reading, Click here!

Custom Search
Swing Chapter 12 (The basics) Menus, Toolbars, and Actions. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 4/5 



Previous Page Previous Page (3/5) - Next Page (5/5) Next Page
Subpages: 1. JMenus, Toolbars, and Actions overview 
2.
Basic text editor: part I - menus 
3.
Basic text editor: part II - Toolbars and Actions 
4. Basic text editor: part III - Custom toolbar components 
5. Basic text editor: part IV- Custom menu components 

12.4  Basic text editor: part III - custom toolbar components

Using Actions to create toolbar buttons is easy, but not always desirable if we wish to have complete control over our toolbar components. In this section we build off of BasicTextEditor and place a JComboBox in the toolbar allowing Font selection. We also use instances of our own custom buttons, SmallButton and SmallToggleButton, in the toolbar. Both of these button classes use different borders to signify different states. SmallButton uses a raised border when the mouse passes over it, no border when the mouse is not within its bounds, and a lowered border when a mouse press occurs. SmallToggleButton uses a raised border when unselected and a lowered border when selected.

Figure 12.5 JToolBar with custom buttons and a JComboBox.

<<file figure12-5.gif>>

The Code: BasicTextEditor.java

see \Chapter12\3

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;

import javax.swing.event.*;

public class BasicTextEditor extends JFrame

{

  // Unchanged code from section 12.3

  protected JComboBox m_cbFonts;

  protected SmallToggleButton m_bBold;

  protected SmallToggleButton m_bItalic;

  // Unchanged code from section 12.3

  protected JMenuBar createMenuBar()

  {

    // Unchanged code from section 12.3

    m_toolBar = new JToolBar();

    JButton bNew = new SmallButton(actionNew,

      "New text");

    m_toolBar.add(bNew);

    JButton bOpen = new SmallButton(actionOpen,

      "Open text file");

    m_toolBar.add(bOpen);

    JButton bSave = new SmallButton(actionSave,

      "Save text file");

    m_toolBar.add(bSave);

    JMenu mFont = new JMenu("Font");

    mFont.setMnemonic('o');

    // Unchanged code from section 12.3

    mFont.addSeparator();

    m_toolBar.addSeparator();

    m_cbFonts = new JComboBox(FONTS);

    m_cbFonts.setMaximumSize(m_cbFonts.getPreferredSize());

    m_cbFonts.setToolTipText("Available fonts");

    ActionListener lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        int index = m_cbFonts.getSelectedIndex();

        if (index < 0)

          return;

        m_fontMenus[index].setSelected(true);

        updateMonitor();

      }

    };

    m_cbFonts.addActionListener(lst);

    m_toolBar.add(m_cbFonts);

    m_bold = new JCheckBoxMenuItem("Bold");

    m_bold.setMnemonic('b');

    Font fn = m_fonts[1].deriveFont(Font.BOLD);

    m_bold.setFont(fn);

    m_bold.setSelected(false);

    m_bold.addActionListener(fontListener);

    mFont.add(m_bold);

    m_italic = new JCheckBoxMenuItem("Italic");

    m_italic.setMnemonic('i');

    fn = m_fonts[1].deriveFont(Font.ITALIC);

    m_italic.setFont(fn);

    m_italic.setSelected(false);

    m_italic.addActionListener(fontListener);

    mFont.add(m_italic);

    menuBar.add(mFont);

    m_toolBar.addSeparator();

    ImageIcon img1 = new ImageIcon("font_bold1.gif");

    ImageIcon img2 = new ImageIcon("font_bold2.gif");

    m_bBold = new SmallToggleButton(false, img1, img2,

      "Bold font");

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        m_bold.setSelected(m_bBold.isSelected());

        updateMonitor();

      }

    };

    m_bBold.addActionListener(lst);

    m_toolBar.add(m_bBold);

    img1 = new ImageIcon("font_italic1.gif");

    img2 = new ImageIcon("font_italic2.gif");

    m_bItalic = new SmallToggleButton(false, img1, img2,

      "Italic font");

    lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        m_italic.setSelected(m_bItalic.isSelected());

        updateMonitor();

      }

    };

    m_bItalic.addActionListener(lst);

    m_toolBar.add(m_bItalic);

    getContentPane().add(m_toolBar, BorderLayout.NORTH);

    return menuBar;

  }

  protected void updateMonitor() {

    int index = -1;

    for (int k=0; k<m_fontMenus.length; k++) {

      if (m_fontMenus[k].isSelected()) {

        index = k;

        break;

      }

    }

    if (index == -1)

      return;

    boolean isBold = m_bold.isSelected();

    boolean isItalic = m_italic.isSelected();

    m_cbFonts.setSelectedIndex(index);

    if (index==2) {   //Courier

      m_bold.setSelected(false);

      m_bold.setEnabled(false);

      m_italic.setSelected(false);

      m_italic.setEnabled(false);

      m_bBold.setSelected(false);

      m_bBold.setEnabled(false);

      m_bItalic.setSelected(false);

      m_bItalic.setEnabled(false);

    }

    else {

      m_bold.setEnabled(true);

      m_italic.setEnabled(true);

      m_bBold.setEnabled(true);

      m_bItalic.setEnabled(true);

    }

    if (m_bBold.isSelected() != isBold)

      m_bBold.setSelected(isBold);

    if (m_bItalic.isSelected() != isItalic)

      m_bItalic.setSelected(isItalic);

    int style = Font.PLAIN;

    if (isBold)

      style |= Font.BOLD;

    if (isItalic)

      style |= Font.ITALIC;

    Font fn = m_fonts[index].deriveFont(style);

    m_monitor.setFont(fn);

    m_monitor.repaint();

  }

  public static void main(String argv[]) {

    new BasicTextEditor();

  }

}

class SmallButton extends JButton implements MouseListener

{

  protected Border m_raised;

  protected Border m_lowered;

  protected Border m_inactive;

  public SmallButton(Action act, String tip) {

    super((Icon)act.getValue(Action.SMALL_ICON));

    m_raised = new BevelBorder(BevelBorder.RAISED);

    m_lowered = new BevelBorder(BevelBorder.LOWERED);

    m_inactive = new EmptyBorder(2, 2, 2, 2);

    setBorder(m_inactive);

    setMargin(new Insets(1,1,1,1));

    setToolTipText(tip);

    addActionListener(act);

    addMouseListener(this);

    setRequestFocusEnabled(false);

  }

  public float getAlignmentY() { return 0.5f; }

  public void mousePressed(MouseEvent e) {

    setBorder(m_lowered);

  }

  public void mouseReleased(MouseEvent e) {

    setBorder(m_inactive);

  }

  public void mouseClicked(MouseEvent e) {}

  public void mouseEntered(MouseEvent e) {

    setBorder(m_raised);

  }

  public void mouseExited(MouseEvent e) {

    setBorder(m_inactive);

  }

}

class SmallToggleButton extends JToggleButton

  implements ItemListener

{

  protected Border m_raised;

  protected Border m_lowered;

  public SmallToggleButton(boolean selected,

   ImageIcon imgUnselected, ImageIcon imgSelected, String tip) {

    super(imgUnselected, selected);

    setHorizontalAlignment(CENTER);

    setBorderPainted(true);

    m_raised = new BevelBorder(BevelBorder.RAISED);

    m_lowered = new BevelBorder(BevelBorder.LOWERED);

    setBorder(selected ? m_lowered : m_raised);

    setMargin(new Insets(1,1,1,1));

    setToolTipText(tip);

    setRequestFocusEnabled(false);

    setSelectedIcon(imgSelected);

    addItemListener(this);

  }

  public float getAlignmentY() { return 0.5f; }

  public void itemStateChanged(ItemEvent e) {

    setBorder(isSelected() ? m_lowered : m_raised);

  }

}

Understanding the Code

Class BasicTextEditor

BasicTextEditor now declares three new instance variables:

JComboBox m_cbFonts: combo box containing available font names.

SmallToggleButton m_bBold: custom toggle button representing the bold font style.

SmallToggleButton m_bItalic: custom toggle button representing the italic font style.

The createMenuBar() method now creates three instances of the SmallButton class (see below) corresponding to our pre-existing "New," "Open," and "Save" toolbar buttons. These are constructed by passing the appropriate Action (which we built in part II) as well as a tooltip String to the SmallButton constructor. Then we create a combo box with all available font names and add it to the toolbar. The setMaximumSize() method is called on the combo box to reduce its size to a necessary maximum (otherwise it will fill all unoccupied space in our toolbar). An ActionListener is then added to monitor combo box selection. This listener selects the corresponding font menu item because the combo box and font radio button menu items must always be in synch. It then calls our updateMonitor() method.

Two SmallToggleButtons are created and added to our toolbar to manage the bold and italic font properties. Each button receives an ActionListener which selects/deselects the corresponding menu item (because both the menu items and toolbar buttons must remain in synch) and calls our updateMonitor() method.

Our updateMonitor() method receives some additional code to provide consistency between our menu items and toolbar controls. This method relies on the state of the menu items, which is why the toolbar components first set the corresponding menu items when selected. The code added here is self-explanatory and just involves enabling/disabling and selecting/deselecting components to preserve consistency.

Class SmallButton

SmallButton represents a small push button to be used in a toolbar. It implements the MouseListener interface to process mouse input. Three instance variables are declared:

Border m_raised: border to be used when the mouse cursor is located over the button.

Border m_lowered: border to be used when the button is pressed.

Border m_inactive: border to be used when the mouse cursor is located outside the button.

The SmallButton constructor takes an Action parameter, which is added as an ActionListener and performs an appropriate action when the button is pressed, and a String representing the tooltip text. Several familiar properties are assigned and the icon encapsulated within the Action is used for this buttons icon. SmallButton also adds itself as a MouseListener and sets its tooltip text to the given String passed to the constructor. Note that the requestFocusEnabled property is set to false so that when this button is clicked focus will not be transferred out of our JTextArea editor component.

The getAlignmentY() method is overriden to return a constant value of 0.5f, indicating that this button should always be placed in the middle of the toolbar in the vertical direction. The remainder of SmallButton represents an implementation of the MouseListener interface which sets the border based on mouse events. The border is set to m_inactive when the is mouse located outside its bounds, m_active when the mouse is located inside its bounds, and m_lowered when the button is pressed.

Class SmallToggleButton

SmallToggleButton extends JToggleButton and implements the ItemListener interface to process changes in the button's selection state. Two instance variables are declared:

Border m_raised: border to be used when the button is unselected (unchecked).

Border m_lowered: border to be used when the button is selected (checked).

The SmallToggleButton constructor takes four arguments:

boolean selected: initial selection state.

ImageIcon imgUnselected: icon for use when unselected.

ImageIcon imgSelected: icon for use when selected.

String tip: tooltip message.

In the constructor, several familiar button properties are set, and a raised or lowered border is assigned depending on the initial selection state. Each instance is added to itself as an ItemListener to receive notification about changes in its selection. Thus the itemStateChanged() method is implemented which simply sets the button's border accordingly corresponding to the new selected state.

Running the Code

Verify that the toolbar components (combobox and toggle buttons) change the editor's font as expected. Check which menu and toolbar components work consistently (menu item selections result in changes in the toolbar controls, and vice versa).

UI Guideline : Tooltip Help Tooltip Help on mouse-over is a "must have" technical addition for small toolbar buttons. The relatively recent innovation of tooltips has greatly improved the usability of toolbars. Don't get caught delivering a toolbar without one, but make sure that your tooltip text is meaningful to the user!



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy