1,编写工具栏非常简单,可以添加组件到工具栏中:
JToolBar bar = new JToolBar();
Bar.add(blueButton);
JToolBar类也有一个用来添加Action对象的方法,可以用Action对象填充工具栏,如下所示:
Bar.add(blueAction);
这个动作的小图标将会显示在工具栏中。
可以使用分隔符吧按钮分开:
bar.addSeparator();
然后,吧工具栏添加到框架中:
add(bar,BorederLaytou.NORTH);
当工具栏没有停靠时,可以制定工具栏的标题:
Bar = new JToolBar(titleString);
在默认情况下,工具栏初始化为水平。如果想要工具栏垂直放置,可以使用下列代码:
Bar = new JToolBar(SwingConstants.VERTIVAL)
或者
Bar = new JToolBar(titleString , SwingConstants.VERTICAL)
2,工具提示
在Swing中,可以调用setToolText方法将工具提示添加到任何一个JComponet组件上:
exitButton.setToolTipText(“Exit”);
还有一种方法是,如果使用ACtion对象,就可以把工具提示与SHORT_DESCRIPTION键关联起来:
exitAction.putValue(Action.SHORT_DESCRIPTION,”Exit”);
例:
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
public class ToolBarTest
{
public static void main(String[] args)
{
ToolBarFrame frame = new ToolBarFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a toolbar and menu for color changes.
*/
class ToolBarFrame extends JFrame
{
public ToolBarFrame()
{
setTitle("ToolBarTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add a panel for color change
panel = new JPanel();
// set up actions
Action blueAction = new ColorAction("Blue",
new ImageIcon("blue-ball.gif"), Color.BLUE);
Action yellowAction = new ColorAction("Yellow",
new ImageIcon("yellow-ball.gif"), Color.YELLOW);
Action redAction = new ColorAction("Red",
new ImageIcon("red-ball.gif"), Color.RED);
Action exitAction = new
AbstractAction("Exit", new ImageIcon("exit.gif"))
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
};
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
// populate tool bar
JToolBar bar = new JToolBar();
bar.add(blueAction);
bar.add(yellowAction);
bar.add(redAction);
bar.addSeparator();
bar.add(exitAction);
add(bar, BorderLayout.NORTH);
// populate menu
JMenu menu = new JMenu("Color");
menu.add(yellowAction);
menu.add(blueAction);
menu.add(redAction);
menu.add(exitAction);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private JPanel panel;
/**
The color action sets the background of the frame to a
given color.
*/
class ColorAction extends AbstractAction
{
public ColorAction(String name, Icon icon, Color c)
{
putValue(Action.NAME, name);
putValue(Action.SMALL_ICON, icon);
putValue(Action.SHORT_DESCRIPTION, name + " background");
putValue("Color", c);
}
public void actionPerformed(ActionEvent event)
{
Color c = (Color) getValue("Color");
panel.setBackground(c);
}
}
}