Java/Swing JFC/Toolbar
Содержание
- 1 Add various buttons to the toolbar
- 2 An example of JToolBar
- 3 A simple frame containing a toolbar made up of several Buttons
- 4 Buttons used in toolbars.
- 5 Create a vertical toolbar
- 6 Create two toolbars
- 7 Determining When a Floatable JToolBar Container Changes Orientation
- 8 Get ToolBar Properties
- 9 Highlighting Buttons in a JToolbar Container While Under the Cursor
- 10 If the toolbar is to be floatable, it must be added to a container with a BorderLayout.
- 11 JToolBar Demo
- 12 JToolbar: Toolbars provide a quick access to the most frequently used commands.
- 13 Preventing a JToolbar Container from Floating
- 14 Shows a vertical toolbar.
- 15 Simple toolbar
- 16 Swing ToolBar Demo
- 17 This class represents a separator for the toolbar buttons.
- 18 Toolbar and menubar
- 19 ToolBar button
- 20 ToolBar Demo 2
- 21 Toolbar Sample
- 22 ToolBar UI Sample
- 23 Working with a Toolbar
Add various buttons to the toolbar
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
public class Main {
public static void main(String[] argv) throws Exception {
JToolBar toolbar = new JToolBar();
ImageIcon icon = new ImageIcon("icon.gif");
Action action = new AbstractAction("Button Label", icon) {
public void actionPerformed(ActionEvent evt) {
}
};
JButton c1 = new JButton(action);
c1.setText(null);
c1.setMargin(new Insets(0, 0, 0, 0));
toolbar.add(c1);
JToggleButton c2 = new JToggleButton(action);
c2.setText(null);
c2.setMargin(new Insets(0, 0, 0, 0));
toolbar.add(c2);
JComboBox c3 = new JComboBox(new String[] { "A", "B", "C" });
c3.setPrototypeDisplayValue("XXXXXXXX"); // Set a desired width
c3.setMaximumSize(c3.getMinimumSize());
toolbar.add(c3);
}
}
An example of JToolBar
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// ToolBarExample.java
// An example of JToolBar. The actions used to build the toolbar are also
// placed in a JMenu to further demonstrate the flexibility of the Action
// class. (See the examples in Chapter 3 for more details on Action.)
//
import java.awt.BorderLayout;
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 ToolBarExample extends JPanel {
public JTextPane pane;
public JMenuBar menuBar;
public JToolBar toolBar;
String fonts[] = { "Serif", "SansSerif", "Monospaced", "Dialog",
"DialogInput" };
public ToolBarExample() {
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);
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);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
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[]) {
ToolBarExample example = new ToolBarExample();
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();
}
}
}
}
A simple frame containing a toolbar made up of several Buttons
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ToolbarFrame1 extends Frame {
Button cutButton, copyButton, pasteButton;
public ToolbarFrame1() {
super("Toolbar Example (AWT)");
setSize(450, 250);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ActionListener printListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println(ae.getActionCommand());
}
};
Panel toolbar = new Panel();
toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));
cutButton = new Button("Cut");
cutButton.addActionListener(printListener);
toolbar.add(cutButton);
copyButton = new Button("Copy");
copyButton.addActionListener(printListener);
toolbar.add(copyButton);
pasteButton = new Button("Paste");
pasteButton.addActionListener(printListener);
toolbar.add(pasteButton);
add(toolbar, BorderLayout.NORTH);
}
public static void main(String args[]) {
ToolbarFrame1 tf1 = new ToolbarFrame1();
tf1.setVisible(true);
}
}
Buttons used in toolbars.
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
/**
* This class represents the buttons used in toolbars.
*
* @author
* @version $Id: JToolbarButton.java 498555 2007-01-22 08:09:33Z cam $
*/
public class JToolbarButton extends JButton {
/**
* Creates a new toolbar button.
*/
public JToolbarButton() {
initialize();
}
/**
* Creates a new toolbar button.
* @param txt The button text.
*/
public JToolbarButton(String txt) {
super(txt);
initialize();
}
/**
* Initializes the button.
*/
protected void initialize() {
if (!System.getProperty("java.version").startsWith("1.3")) {
setOpaque(false);
setBackground(new java.awt.Color(0, 0, 0, 0));
}
setBorderPainted(false);
setMargin(new Insets(2, 2, 2, 2));
addMouseListener(new MouseListener());
}
/**
* To manage the mouse interactions.
*/
protected class MouseListener extends MouseAdapter {
public void mouseEntered(MouseEvent ev) {
setBorderPainted(true);
}
public void mouseExited(MouseEvent ev) {
setBorderPainted(false);
}
}
}
Create a vertical toolbar
import javax.swing.JToolBar;
public class Main {
public static void main(String[] argv) throws Exception {
JToolBar toolbar = new JToolBar(null, JToolBar.VERTICAL);
// Get current orientation
int orient = toolbar.getOrientation();
}
}
Create two toolbars
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
public class Toolbars {
public static void main(String[] args) {
JToolBar toolbar1 = new JToolBar();
JToolBar toolbar2 = new JToolBar();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton newb = new JButton(new ImageIcon("new.png"));
JButton openb = new JButton(new ImageIcon("open.png"));
JButton saveb = new JButton(new ImageIcon("save.png"));
toolbar1.add(newb);
toolbar1.add(openb);
toolbar1.add(saveb);
toolbar1.setAlignmentX(0);
JButton exitb = new JButton(new ImageIcon("exit.png"));
toolbar2.add(exitb);
toolbar2.setAlignmentX(0);
exitb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(toolbar1);
panel.add(toolbar2);
JFrame f = new JFrame();
f.add(panel, BorderLayout.NORTH);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Determining When a Floatable JToolBar Container Changes Orientation
import javax.swing.JToolBar;
public class Main {
public static void main(String[] argv) throws Exception {
JToolBar toolbar = new JToolBar();
toolbar.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
if ("orientation".equals(propName)) {
Integer oldValue = (Integer) evt.getOldValue();
Integer newValue = (Integer) evt.getNewValue();
if (newValue.intValue() == JToolBar.HORIZONTAL) {
System.out.println("horizontal orientation");
} else {
System.out.println("vertical orientation");
}
}
}
});
}
}
Get ToolBar Properties
import javax.swing.JToolBar;
import javax.swing.UIManager;
public class GetToolBarProperties {
public static void main(String args[]) {
JToolBar toolbar = new JToolBar();
String classID = toolbar.getUIClassID();
System.out.println(classID);
String className = (String) UIManager.get(classID);
System.out.println(className);
}
}
Highlighting Buttons in a JToolbar Container While Under the Cursor
import javax.swing.JToolBar;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a horizontal toolbar
JToolBar toolbar = new JToolBar();
// Get current rollover mode
boolean b = toolbar.isRollover();
// Enable rollover mode
toolbar.setRollover(true);
}
}
If the toolbar is to be floatable, it must be added to a container with a BorderLayout.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class Main {
public static void main(String[] argv) throws Exception {
// Add the toolbar to a frame
JFrame frame = new JFrame();
JToolBar toolbar = new JToolBar();
frame.getContentPane().add(toolbar, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
}
}
JToolBar Demo
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class SwingToolBarSample extends JPanel {
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);
JToolBar toolbar = new JToolBar();
toolbar.putClientProperty("JToolBar.isRollover", Boolean.TRUE);
for (int i = 0, n = buttonColors.length; i < 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);
}
}
Action action = new ActionMenuSample.ShowAction(frame);
toolbar.add(action);
Container contentPane = frame.getContentPane();
contentPane.add(toolbar, BorderLayout.NORTH);
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
contentPane.add(pane, BorderLayout.CENTER);
frame.setSize(350, 150);
frame.setVisible(true);
}
}
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);
}
}
class ActionMenuSample {
public static class ShowAction extends AbstractAction {
Component parentComponent;
public ShowAction(Component parentComponent) {
super("About");
putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
this.parentComponent = parentComponent;
}
public void actionPerformed(ActionEvent actionEvent) {
Runnable runnable = new Runnable() {
public void run() {
JOptionPane.showMessageDialog(parentComponent,
"About Life", "About Box V1.0",
JOptionPane.INFORMATION_MESSAGE);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public static void main(String args[]) {
JFrame frame = new JFrame("Action Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Action showAction = new ShowAction(frame);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic("f");
JMenuItem newMenuItem = new JMenuItem("New", "N");
fileMenu.add(newMenuItem);
JMenuItem openMenuItem = new JMenuItem("Open", "O");
fileMenu.add(openMenuItem);
JMenuItem closeMenuItem = new JMenuItem("Close", "C");
fileMenu.add(closeMenuItem);
fileMenu.addSeparator();
JMenuItem saveMenuItem = new JMenuItem("Save", "S");
fileMenu.add(saveMenuItem);
fileMenu.add(showAction);
fileMenu.addSeparator();
JMenuItem exitMenuItem = new JMenuItem("Exit", "X");
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
JMenuItem cutMenuItem = new JMenuItem("Cut", "T");
KeyStroke ctrlXKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X,
Event.CTRL_MASK);
cutMenuItem.setAccelerator(ctrlXKeyStroke);
editMenu.add(cutMenuItem);
JMenuItem copyMenuItem = new JMenuItem("Copy", "C");
KeyStroke ctrlCKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C,
Event.CTRL_MASK);
copyMenuItem.setAccelerator(ctrlCKeyStroke);
editMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste", "P");
KeyStroke ctrlVKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V,
Event.CTRL_MASK);
pasteMenuItem.setAccelerator(ctrlVKeyStroke);
pasteMenuItem.setEnabled(false);
editMenu.add(pasteMenuItem);
editMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find", "F");
KeyStroke f3KeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0);
findMenuItem.setAccelerator(f3KeyStroke);
editMenu.add(findMenuItem);
editMenu.setMnemonic("e");
editMenu.add(showAction);
menuBar.add(editMenu);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
JToolbar: Toolbars provide a quick access to the most frequently used commands.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
public class SimpleToolbar {
public static void main(String[] args) {
JFrame f = new JFrame();
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
menubar.add(file);
f.setJMenuBar(menubar);
JToolBar toolbar = new JToolBar();
ImageIcon icon = new ImageIcon("exit.png");
JButton exit = new JButton(icon);
toolbar.add(exit);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
f.add(toolbar, BorderLayout.NORTH);
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Preventing a JToolbar Container from Floating
import javax.swing.JToolBar;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a horizontal toolbar
JToolBar toolbar = new JToolBar();
// Get current floatability
boolean b = toolbar.isFloatable();
// Disable floatability
toolbar.setFloatable(false);
}
}
Shows a vertical toolbar.
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class VerticalToolbar {
public static void main(String[] args) {
JToolBar toolbar = new JToolBar(JToolBar.VERTICAL);
JButton selectb = new JButton(new ImageIcon("select.gif"));
JButton freehandb = new JButton(new ImageIcon("freehand.gif"));
JButton shapeedb = new JButton(new ImageIcon("shapeed.gif"));
JButton penb = new JButton(new ImageIcon("pen.gif"));
toolbar.add(selectb);
toolbar.add(freehandb);
toolbar.add(shapeedb);
toolbar.add(penb);
JFrame f = new JFrame();
f.add(toolbar, BorderLayout.WEST);
f.setSize(250, 350);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Simple toolbar
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
public class SimpleToolbar extends JFrame {
public static final String FontNames[] = { "Serif", "SansSerif", "Courier" };
protected Font fonts[];
protected JFileChooser fileChooser = new JFileChooser();
protected JToolBar toolBar;
protected JComboBox cbFonts;
protected SmallToggleButton bBold;
protected SmallToggleButton bItalic;
public SimpleToolbar() {
super();
setSize(450, 350);
fonts = new Font[FontNames.length];
for (int k = 0; k < FontNames.length; k++)
fonts[k] = new Font(FontNames[k], Font.PLAIN, 12);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
createToolBar();
setVisible(true);
}
protected void createToolBar() {
ImageIcon iconNew = new ImageIcon("file_new.gif");
Action actionNew = new AbstractAction("New", iconNew) {
public void actionPerformed(ActionEvent e) {
;
}
};
ImageIcon iconOpen = new ImageIcon("file_open.gif");
Action actionOpen = new AbstractAction("Open...", iconOpen) {
public void actionPerformed(ActionEvent e) {
}
};
ImageIcon iconSave = new ImageIcon("file_save.gif");
Action actionSave = new AbstractAction("Save...", iconSave) {
public void actionPerformed(ActionEvent e) {
}
};
Action actionExit = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
toolBar = new JToolBar();
JButton bNew = new SmallButton(actionNew, "New text");
toolBar.add(bNew);
JButton bOpen = new SmallButton(actionOpen, "Open text file");
toolBar.add(bOpen);
JButton bSave = new SmallButton(actionSave, "Save text file");
toolBar.add(bSave);
ActionListener fontListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
};
toolBar.addSeparator();
cbFonts = new JComboBox(FontNames);
cbFonts.setMaximumSize(cbFonts.getPreferredSize());
cbFonts.setToolTipText("Available fonts");
ActionListener lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = cbFonts.getSelectedIndex();
if (index < 0)
return;
}
};
cbFonts.addActionListener(lst);
toolBar.add(cbFonts);
toolBar.addSeparator();
ImageIcon img1 = new ImageIcon("font_bold1.gif");
ImageIcon img2 = new ImageIcon("font_bold2.gif");
bBold = new SmallToggleButton(false, img1, img2, "Bold font");
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
};
bBold.addActionListener(lst);
toolBar.add(bBold);
img1 = new ImageIcon("font_italic1.gif");
img2 = new ImageIcon("font_italic2.gif");
bItalic = new SmallToggleButton(false, img1, img2, "Italic font");
lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
};
bItalic.addActionListener(lst);
toolBar.add(bItalic);
getContentPane().add(toolBar, BorderLayout.NORTH);
}
public static void main(String[] a){
new SimpleToolbar();
}
}
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 raised;
protected Border lowered;
public SmallToggleButton(boolean selected, ImageIcon imgUnselected,
ImageIcon imgSelected, String tip) {
super(imgUnselected, selected);
setHorizontalAlignment(CENTER);
setBorderPainted(true);
raised = new BevelBorder(BevelBorder.RAISED);
lowered = new BevelBorder(BevelBorder.LOWERED);
setBorder(selected ? lowered : 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() ? lowered : raised);
}
}
Swing ToolBar Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* SwingToolBarDemo.java is a 1.4 application that relies on having the Java Look and
* Feel Graphics Repository (jlfgr-1_0.jar) in the class path. You can download
* it from http://developer.java.sun.ru/developer/techDocs/hi/repository/. When
* running SwingToolBarDemo from the command line (rather than Java Web Start) put
* jlfgr-1_0.jar in the class path using one of the following commands (assuming
* jlfgr-1_0.jar is in a subdirectory named jars):
*
* java -cp .;jars/jlfgr-1_0.jar SwingToolBarDemo [Microsoft Windows] java -cp
* .:jars/jlfgr-1_0.jar SwingToolBarDemo [UNIX]
*
* If that doesn"t work, try putting quotation marks around the path:
*
* java -cp ".;jars/jlfgr-1_0.jar" SwingToolBarDemo [UNIX shell on Win32]
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
public class SwingToolBarDemo extends JPanel implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public SwingToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other", "Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP, "Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other", "Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand, String toolTipText, String altText) {
//Look for the image.
String imgLocation = "toolbarButtonGraphics/navigation/" + imageName
+ ".gif";
URL imageURL = SwingToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have " + description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("SwingToolBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
SwingToolBarDemo newContentPane = new SwingToolBarDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This class represents a separator for the toolbar buttons.
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
/**
* This class represents a separator for the toolbar buttons.
*
* @author
* @version $Id: JToolbarSeparator.java 475477 2006-11-15 22:44:28Z cam $
*/
public class JToolbarSeparator extends JComponent {
/**
* Creates a new JToolbarSeparator object.
*/
public JToolbarSeparator() {
setMaximumSize(new Dimension(15, Integer.MAX_VALUE));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
int pos = size.width / 2;
g.setColor(Color.gray);
g.drawLine(pos, 3, pos, size.height - 5);
g.drawLine(pos, 2, pos + 1, 2);
g.setColor(Color.white);
g.drawLine(pos + 1, 3, pos + 1, size.height - 5);
g.drawLine(pos, size.height - 4, pos + 1, size.height - 4);
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToolBar;
public class ToolbarDemo extends JFrame {
public static final String FontNames[] = { "Serif", "SansSerif", "Courier" };
protected Font fonts[];
protected JMenuItem[] fontMenus;
protected JCheckBoxMenuItem boldMenu = new JCheckBoxMenuItem("Bold");
protected JCheckBoxMenuItem italicMenu = new JCheckBoxMenuItem("Italic");
protected JToolBar toolBar;
public ToolbarDemo() {
super("Toolbars & actions");
setSize(450, 350);
fonts = new Font[FontNames.length];
for (int i = 0; i < FontNames.length; i++)
fonts[i] = new Font(FontNames[i], Font.PLAIN, 12);
JMenuBar menuBar = createMenuBar();
setJMenuBar(menuBar);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
updateMonitor();
setVisible(true);
}
protected JMenuBar createMenuBar() {
final JMenuBar menuBar = new JMenuBar();
JMenu mFile = new JMenu("File");
mFile.setMnemonic("f");
ImageIcon iconNew = new ImageIcon("file_new.gif");
Action actionNew = new AbstractAction("New", iconNew) {
public void actionPerformed(ActionEvent e) {
System.out.println("new action");
}
};
JMenuItem item = mFile.add(actionNew);
mFile.add(item);
ImageIcon iconOpen = new ImageIcon("file_open.gif");
Action actionOpen = new AbstractAction("Open...", iconOpen) {
public void actionPerformed(ActionEvent e) {
System.out.println("open action");
}
};
item = mFile.add(actionOpen);
mFile.add(item);
ImageIcon iconSave = new ImageIcon("file_save.gif");
Action actionSave = new AbstractAction("Save...", iconSave) {
public void actionPerformed(ActionEvent e) {
System.out.println("save action");
}
};
item = mFile.add(actionSave);
mFile.add(item);
mFile.addSeparator();
Action actionExit = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
};
item = mFile.add(actionExit);
item.setMnemonic("x");
menuBar.add(mFile);
toolBar = new JToolBar();
JButton btn1 = toolBar.add(actionNew);
btn1.setToolTipText("New text");
JButton btn2 = toolBar.add(actionOpen);
btn2.setToolTipText("Open text file");
JButton btn3 = toolBar.add(actionSave);
btn3.setToolTipText("Save text file");
ActionListener fontListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateMonitor();
}
};
JMenu mFont = new JMenu("Font");
mFont.setMnemonic("o");
ButtonGroup group = new ButtonGroup();
fontMenus = new JMenuItem[FontNames.length];
for (int k = 0; k < FontNames.length; k++) {
int m = k + 1;
fontMenus[k] = new JRadioButtonMenuItem(m + " " + FontNames[k]);
boolean selected = (k == 0);
fontMenus[k].setSelected(selected);
fontMenus[k].setMnemonic("1" + k);
fontMenus[k].setFont(fonts[k]);
fontMenus[k].addActionListener(fontListener);
group.add(fontMenus[k]);
mFont.add(fontMenus[k]);
}
mFont.addSeparator();
boldMenu.setMnemonic("b");
Font fn = fonts[1].deriveFont(Font.BOLD);
boldMenu.setFont(fn);
boldMenu.setSelected(false);
boldMenu.addActionListener(fontListener);
mFont.add(boldMenu);
italicMenu.setMnemonic("i");
fn = fonts[1].deriveFont(Font.ITALIC);
italicMenu.setFont(fn);
italicMenu.setSelected(false);
italicMenu.addActionListener(fontListener);
mFont.add(italicMenu);
menuBar.add(mFont);
getContentPane().add(toolBar, BorderLayout.NORTH);
return menuBar;
}
protected void updateMonitor() {
int index = -1;
for (int k = 0; k < fontMenus.length; k++) {
if (fontMenus[k].isSelected()) {
index = k;
break;
}
}
if (index == -1)
return;
if (index == 2) // Courier
{
boldMenu.setSelected(false);
boldMenu.setEnabled(false);
italicMenu.setSelected(false);
italicMenu.setEnabled(false);
} else {
boldMenu.setEnabled(true);
italicMenu.setEnabled(true);
}
int style = Font.PLAIN;
if (boldMenu.isSelected())
style |= Font.BOLD;
if (italicMenu.isSelected())
style |= Font.ITALIC;
Font fn = fonts[index].deriveFont(style);
}
public static void main(String argv[]) {
new ToolbarDemo();
}
}
ToolBar button
//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2006.
//
//All Rights Reserved.
import java.awt.Insets;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
/**
* ToolBar button.
*
* @author Frederik Dietz
*/
@SuppressWarnings("serial")
public class ToolBarButton extends JButton {
public ToolBarButton(String text, Icon icon) {
super(text, icon);
initButton();
}
public ToolBarButton() {
super();
initButton();
}
public ToolBarButton(Action action) {
super(action);
initButton();
}
private void initButton() {
setRolloverEnabled(true);
setRequestFocusEnabled(false);
setMargin(new Insets(1, 1, 1, 1));
putClientProperty("JToolBar.isRollover", Boolean.TRUE);
}
public boolean isFocusTraversable() {
return isRequestFocusEnabled();
}
/**
* @see javax.swing.JButton#updateUI()
*/
public void updateUI() {
super.updateUI();
setRolloverEnabled(true);
putClientProperty("JToolBar.isRollover", Boolean.TRUE);
}
}
ToolBar Demo 2
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* ToolBarDemo2.java is a 1.4 application that relies on having the Java Look
* and Feel Graphics Repository (jlfgr-1_0.jar) in the class path. You can
* download it from
* http://developer.java.sun.ru/developer/techDocs/hi/repository/. When running
* ToolBarDemo2 from the command line (rather than Java Web Start) put
* jlfgr-1_0.jar in the class path using one of the following commands (assuming
* jlfgr-1_0.jar is in a subdirectory named jars):
*
* java -cp .;jars/jlfgr-1_0.jar ToolBarDemo2 [Microsoft Windows] java -cp
* .:jars/jlfgr-1_0.jar ToolBarDemo2 [UNIX]
*
* If that doesn"t work, try putting quotation marks around the path:
*
* java -cp ".;jars/jlfgr-1_0.jar" ToolBarDemo2 [UNIX shell on Win32]
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
public class ToolBarDemo2 extends JPanel implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
static final private String SOMETHING_ELSE = "other";
static final private String TEXT_ENTERED = "text";
public ToolBarDemo2() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
toolBar.setFloatable(false);
toolBar.setRollover(true);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other", "Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP, "Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other", "Next");
toolBar.add(button);
//separator
toolBar.addSeparator();
//fourth button
button = new JButton("Another button");
button.setActionCommand(SOMETHING_ELSE);
button.setToolTipText("Something else");
button.addActionListener(this);
toolBar.add(button);
//fifth component is NOT a button!
JTextField textField = new JTextField("A text field");
textField.setColumns(10);
textField.addActionListener(this);
textField.setActionCommand(TEXT_ENTERED);
toolBar.add(textField);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand, String toolTipText, String altText) {
//Look for the image.
String imgLocation = "toolbarButtonGraphics/navigation/" + imageName
+ ".gif";
URL imageURL = ToolBarDemo2.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
} else if (SOMETHING_ELSE.equals(cmd)) { // fourth button clicked
description = "done something else.";
} else if (TEXT_ENTERED.equals(cmd)) { // text field
JTextField tf = (JTextField) e.getSource();
String text = tf.getText();
tf.setText("");
description = "done something with this text: " + newline + " \""
+ text + "\"";
}
displayResult("If this were a real app, it would have " + description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("ToolBarDemo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
ToolBarDemo2 newContentPane = new ToolBarDemo2();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Toolbar Sample
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.plaf.metal.MetalIconFactory;
public class ToolbarSample {
public static void main(String args[]) {
JFrame f = new JFrame("JToolbar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JToolBar toolbar = new JToolBar();
Icon icon = MetalIconFactory.getFileChooserDetailViewIcon();
JToggleButton button = new JToggleButton(icon);
toolbar.add(button);
icon = MetalIconFactory.getFileChooserHomeFolderIcon();
button = new JToggleButton(icon);
toolbar.add(button);
icon = MetalIconFactory.getFileChooserListViewIcon();
button = new JToggleButton(icon);
toolbar.add(button);
content.add(toolbar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
}
}
ToolBar UI Sample
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
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 ToolBarUISample {
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 < 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);
}
}
Working with a Toolbar
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
public class ToolBarTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
JToolBar bar;
bar = new JToolBar();
JToggleButton jb;
for (int i = 0; i < 8; i++) {
jb = new JToggleButton("" + i);
bar.add(jb);
if (i == 5) {
bar.addSeparator();
}
}
contentPane.add(bar, BorderLayout.NORTH);
frame.setSize(300, 300);
frame.show();
}
}