Swing - SPLessons

Swing Toolbar

Chapter 19

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Toolbar

Swing Toolbar

shape Description

Now a days many applications are available in the market, all these applications will come up with some extra features and the look and feel of those applications and components will be more efficient. Swing Toolbar is used to select particular element such as desktop and various applications.
The best example for Swing Toolbar is i.e while browsing something in the online user needs to perform forward and backward actions so it is possible by Toolbar. The sample example of Swing Toolbar as shown follows.

Sample Toolbar

shape Example

The basic example of Swing Toolbar as shown follows.

ToolBarSample.java

package swing;//created a package
<pre>
import java.awt.BorderLayout;//import all the required pacakages
import java.awt.Container;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;

public class ToolBarSample {//creatd a class with the name ToolBarSample
  public static void main(final String args[]) {
    JFrame frame = new JFrame("JToolBar Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//window needs to be closed

    JToolBar toolbar = new JToolBar();
    toolbar.setRollover(true);

    JButton button = new JButton("button");//here created a button with the name Button
    toolbar.add(button);
    toolbar.addSeparator();
    
    toolbar.add(new JButton("button 2"));//here also created a button with the name Button 2
    
    toolbar.add(new JComboBox(new String[]{"1","2","3"}));//here created combo box and given selection values are as 1,2,3 
    
    Container contentPane = frame.getContentPane();
    contentPane.add(toolbar, BorderLayout.NORTH);//Here user can add like east,south also
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    contentPane.add(pane, BorderLayout.CENTER);
    frame.setSize(350, 150);//created size of a window
    frame.setVisible(true);//it should always be as true to visible the window
  }
}

Here created a button and button2 that should be added into the toolbar, created combo box also to select the input.

JButton button = new JButton("button");//here created a button with the name Button
    toolbar.add(button);
    toolbar.addSeparator();
     
    toolbar.add(new JButton("button 2"));//here also created a button with the name Button 2
     
    toolbar.add(new JComboBox(new String[]{"1","2","3"}));

Here created window application direction also to place on the screen with the size.

contentPane.add(pane, BorderLayout.CENTER);
    frame.setSize(350, 150);//created size of a window
    frame.setVisible(true);

Output:
After executing the above code, output will be as follows.

Here two buttons and combo box has been created, each will have their own functionality, in the combo box user can select the elements and here we can the various menu also that will be explained in next examples.

Adding Items

shape Example

Here user can add different elements into the toolbar will be shown as follows.
AddToolbars.java

package swing;//created a package

import java.awt.BorderLayout;//imort all required pacakges
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.border.BevelBorder;

public class AddToolbars extends JPanel {//created a class AddToolbars that should extend JPanel

  public JTextPane pane;//created pane

  public JMenuBar menuBar;//created menubar

  public JToolBar toolBar;//created toolbar

  String fonts[] = { "Serif", "SansSerif", "Monospaced", "Dialog",
      "DialogInput" };//these are the fonts needs select depends on the requirement

  public AddToolbars() {
    menuBar = new JMenuBar();

    // Create a set of actions to use in both the menu and toolbar
    DemoAction leftJustifyAction = new DemoAction("Left", new ImageIcon(
        "1.gif"), "Left justify text", 'L');
    DemoAction rightJustifyAction = new DemoAction("Right", new ImageIcon(
        "2.gif"), "Right justify text", 'R');
    DemoAction centerJustifyAction = new DemoAction("Center",
        new ImageIcon("3.gif"), "Center justify text", 'M');
    DemoAction fullJustifyAction = new DemoAction("Full", new ImageIcon(
        "4.gif"), "Full justify text", 'F');

    JMenu formatMenu = new JMenu("Justify");
    formatMenu.add(leftJustifyAction);//based onthe clicking it happens
    formatMenu.add(rightJustifyAction);
    formatMenu.add(centerJustifyAction);
    formatMenu.add(fullJustifyAction);

    menuBar.add(formatMenu);

    toolBar = new JToolBar("Formatting");
    toolBar.add(leftJustifyAction);
    toolBar.add(rightJustifyAction);
    toolBar.add(centerJustifyAction);
    toolBar.add(fullJustifyAction);

    toolBar.addSeparator();
    JLabel label = new JLabel("Font");
    toolBar.add(label);

    toolBar.addSeparator();
    JComboBox combo = new JComboBox(fonts);//in combo box fonts have been created. 
    combo.addActionListener(new ActionListener() {//ActionListener interface needs to be implemented  for the event
      public void actionPerformed(ActionEvent e) {//depends on the event it will be performed
        try {
          pane.getStyledDocument().insertString(
              0,
              "Font ["
                  + ((JComboBox) e.getSource())
                      .getSelectedItem() + "] chosen!\n",
              null);
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    });
    toolBar.add(combo);

    //  Disable one of the Actions
    fullJustifyAction.setEnabled(false);
  }

  public static void main(String s[]) {

	  AddToolbars example = new AddToolbars();
    example.pane = new JTextPane();
    example.pane.setPreferredSize(new Dimension(250, 250));
    example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));
    example.toolBar.setMaximumSize(example.toolBar.getSize());

    JFrame frame = new JFrame("Menu Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(example.menuBar);
    frame.getContentPane().add(example.toolBar, BorderLayout.NORTH);
    frame.getContentPane().add(example.pane, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }

  class DemoAction extends AbstractAction {

    public DemoAction(String text, Icon icon, String description,
        char accelerator) {
      super(text, icon);
      putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(accelerator,
          Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
      putValue(SHORT_DESCRIPTION, description);
    }

    public void actionPerformed(ActionEvent e) {
      try {
        pane.getStyledDocument().insertString(0,
            "Action [" + getValue(NAME) + "] performed!\n", null);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
}

Here created a class that should extends JPanel as follows.

public class AddToolbars extends JPanel {//created a class AddToolbars that should extend JPanel
 

Create menubar, pane, toolbar and create font size and font text style as shown follows.

public JTextPane pane;//created pane
 
  public JMenuBar menuBar;//created menubar
 
  public JToolBar toolBar;//created toolbar
 
  String fonts[] = { "Serif", "SansSerif", "Monospaced", "Dialog",
      "DialogInput" };//these are the fonts needs select depends on the requirement

Create actions while performing on menu and toolbars as follows.

DemoAction leftJustifyAction = new DemoAction("Left", new ImageIcon(
        "1.gif"), "Left justify text", 'L');
    DemoAction rightJustifyAction = new DemoAction("Right", new ImageIcon(
        "2.gif"), "Right justify text", 'R');
    DemoAction centerJustifyAction = new DemoAction("Center",
        new ImageIcon("3.gif"), "Center justify text", 'M');
    DemoAction fullJustifyAction = new DemoAction("Full", new ImageIcon(
        "4.gif"), "Full justify text", 'F');

Create font size and implement ActionListener interface to listen the events as shown follows.

JComboBox combo = new JComboBox(fonts);//in combo box fonts have been created. 
    combo.addActionListener(new ActionListener() {//ActionListener interface needs to be implemented  for the event
      public void actionPerformed(ActionEvent e) {

Create title of the window and add instance of the window such as closing functions as follows.

JFrame frame = new JFrame("Menu Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(example.menuBar);
    frame.getContentPane().add(example.toolBar, BorderLayout.NORTH);
    frame.getContentPane().add(example.pane, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);

Output:
After executing the above code, output will be as follows.

In this image combo box inserted, by clicking on the combo box user can select the needed font areas will be displayed, when click on Serif then it displays that Font[Serif]chosen! .

ToolBar UI

shape Example

Every application needs effectiveness, to do this cient will follow some protocols such as adding colors to the applications. The look and feel of application should be effective. Swing Toolbar with user interface example has been shown as follows.

ToolBarUIEx.java

package swing;//create a package

import java.awt.BorderLayout;//import all the packages
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.plaf.ToolBarUI;
import javax.swing.plaf.metal.MetalToolBarUI;

public class ToolBarUIEx {

  private static final int COLOR_POSITION = 0;

  private static final int STRING_POSITION = 1;

  static Object buttonColors[][] = { { Color.red, "red" },
      { Color.blue, "blue" }, { Color.green, "green" },
      { Color.black, "black" }, null, // separator
      { Color.cyan, "cyan" } };

  public static void main(String args[]) {

    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getActionCommand());
      }
    };

    JFrame frame = new JFrame("JToolBar Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ToolBarUI toolbarUI = new CustomToolBarUI();
    Icon imageIcon = new ImageIcon("World.gif");
    UIManager.put(CustomToolBarUI.FRAME_IMAGEICON, imageIcon);

    JToolBar toolbar = new JToolBar();
    toolbar.setUI(toolbarUI);
    toolbar.putClientProperty("JToolBar.isRollover", Boolean.TRUE);

    for (int i = 0, n = buttonColors.length; i &lt; n; i++) {
      Object color[] = buttonColors[i];
      if (color == null) {
        toolbar.addSeparator();
      } else {
        Icon icon = new DiamondIcon((Color) color[COLOR_POSITION],
            true, 20, 20);
        JButton button = new JButton(icon);
        button.setActionCommand((String) color[STRING_POSITION]);
        button.addActionListener(actionListener);
        toolbar.add(button);
      }
    }

    Container contentPane = frame.getContentPane();
    contentPane.add(toolbar, BorderLayout.NORTH);
    frame.setSize(350, 150);
    frame.setVisible(true);
  }
}

class CustomToolBarUI extends MetalToolBarUI {
  public final static String FRAME_IMAGEICON = "ToolBar.frameImageIcon";

  protected JFrame createFloatingFrame(JToolBar toolbar) {
    JFrame frame = new JFrame(toolbar.getName());
    frame.setResizable(false);
    Icon icon = UIManager.getIcon(FRAME_IMAGEICON);
    if (icon instanceof ImageIcon) {
      Image iconImage = ((ImageIcon) icon).getImage();
      frame.setIconImage(iconImage);
    }
    WindowListener windowListener = createFrameListener();
    frame.addWindowListener(windowListener);
    return frame;
  }
}

class DiamondIcon implements Icon {
  private Color color;

  private boolean selected;

  private int width;

  private int height;

  private Polygon poly;

  private static final int DEFAULT_WIDTH = 10;

  private static final int DEFAULT_HEIGHT = 10;

  public DiamondIcon(Color color) {
    this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }

  public DiamondIcon(Color color, boolean selected) {
    this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
  }

  public DiamondIcon(Color color, boolean selected, int width, int height) {
    this.color = color;
    this.selected = selected;
    this.width = width;
    this.height = height;
    initPolygon();
  }

  private void initPolygon() {
    poly = new Polygon();
    int halfWidth = width / 2;
    int halfHeight = height / 2;
    poly.addPoint(0, halfHeight);
    poly.addPoint(halfWidth, 0);
    poly.addPoint(width, halfHeight);
    poly.addPoint(halfWidth, height);
  }

  public int getIconHeight() {
    return height;
  }

  public int getIconWidth() {
    return width;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(color);
    g.translate(x, y);
    if (selected) {
      g.fillPolygon(poly);
    } else {
      g.drawPolygon(poly);
    }
    g.translate(-x, -y);
  }
}

Create button icons, add the colors to the buttons and add buttons to the toolbar.ActionListener should perform on the buttons.

Icon icon = new DiamondIcon((Color) color[COLOR_POSITION],
            true, 20, 20);
        JButton button = new JButton(icon);
        button.setActionCommand((String) color[STRING_POSITION]);
        button.addActionListener(actionListener);
        toolbar.add(button);

Create the frame and add WindowListener to the frame.

 protected JFrame createFloatingFrame(JToolBar toolbar) {
    JFrame frame = new JFrame(toolbar.getName());
    frame.setResizable(false);

 WindowListener windowListener = createFrameListener();
    frame.addWindowListener(windowListener);
    return frame;

Create initPolygon(), add height and width of the diamond icon to the method.

private void initPolygon() {
    poly = new Polygon();
    int halfWidth = width / 2;
    int halfHeight = height / 2;
    poly.addPoint(0, halfHeight);
    poly.addPoint(halfWidth, 0);
    poly.addPoint(width, halfHeight);
    poly.addPoint(halfWidth, height);
  }

Output:
After executing the above code output will be as follows.

Here user can select the color depends on the requirement and these will be useful in developing applications to color the text or background colors.

Summary

shape Description

  • Swing Toolbar – To add the more effectiveness to the application different buttons will be added to the applications.
  • Swing Toolbar – Toolbar can have the ability to mange the software by providing row boxes.
  • To move forward and backward tool bars will be useful.