import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JToolBarUseDemo extends JPanel implements ActionListener {
private JTextArea textArea;
private static String NEW = "new";
private static String OPEN = "open";
private static String SAVE = "save";
private static String SEARCH = "search";
public JToolBarUseDemo() {
super(new BorderLayout());
JToolBar toolBar = new JToolBar();
addButtons(toolBar);
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
setPreferredSize(new Dimension(450, 110));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
button = makeButton("New", NEW, "新建", NEW);
toolBar.add(button);
button = makeButton("Open", OPEN, "打开", OPEN);
toolBar.add(button);
button = makeButton("Save", SAVE, "保存", SAVE);
toolBar.add(button);
button = makeButton("Search", SEARCH, "搜索", SEARCH);
toolBar.add(button);
}
protected JButton makeButton(String imageName, String actionCommand,String toolTipText, String altText) {
String imgLocation = "chapter11//" + imageName + ".gif";
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
button.setIcon(new ImageIcon(imgLocation));
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
if (NEW.equals(cmd)) {
description = " <" + NEW + ">工具按钮";
} else if (OPEN.equals(cmd)) {
description = " <" + OPEN + ">工具按钮";
} else if (SAVE.equals(cmd)) {
description = " <" + SAVE + ">工具按钮";
} else if (SEARCH.equals(cmd)) {
description = " <" + SEARCH + ">工具按钮";
}
textArea.append(description + "/n");
}
public static void main(String[] args) {
JFrame frame = new JFrame("JToolBarUseDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToolBarUseDemo newPane = new JToolBarUseDemo();
newPane.setOpaque(false);
frame.setContentPane(newPane);
frame.pack();
frame.setVisible(true);
}
}