構建包含「打開、保存、搜索」三個圖標按鈕的工具欄,按鈕支持工具提示、鍵盤助記符、點擊後在下方文本區輸出操作日誌。工具欄可拖拽浮動/停靠(JToolBar 默認特性)。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.URL;
public class ToolBarDemo extends JPanel implements ActionListener {
private JTextArea logArea;
private static final String OPEN = "OPEN", SAVE = "SAVE", SEARCH = "SEARCH";
private final String NL = "\n";
public ToolBarDemo() {
super(new BorderLayout());
// 1. 工具欄
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(true); // 允許拖拽浮動
addButtons(toolBar);
add(toolBar, BorderLayout.PAGE_START);
// 2. 日誌輸出區
logArea = new JTextArea(15, 30);
logArea.setEditable(false);
add(new JScrollPane(logArea), BorderLayout.CENTER);
setPreferredSize(new Dimension(450, 300));
}
private void addButtons(JToolBar tb) {
tb.add(makeButton("Open16", OPEN, "打開一個文件", "打開"));
tb.add(makeButton("Save16", SAVE, "保存當前文件", "保存"));
tb.add(makeButton("Search16", SEARCH, "搜索文件內容", "搜索"));
}
private JButton makeButton(String imgName, String cmd, String tip, String altText) {
JButton btn = new JButton();
btn.setActionCommand(cmd);
btn.setToolTipText(tip);
btn.addActionListener(this);
URL imgUrl = ToolBarDemo.class.getResource("images/" + imgName + ".gif");
if (imgUrl != null) {
btn.setIcon(new ImageIcon(imgUrl));
} else {
btn.setText(altText); // 圖標缺失時降級顯示文本
System.err.println("資源未找到: images/" + imgName + ".gif");
}
return btn;
}
@Override
public void actionPerformed(ActionEvent e) {
String desc = switch (e.getActionCommand()) {
case OPEN -> "打開文件操作";
case SAVE -> "保存文件操作";
case SEARCH -> "搜索字符操作";
default -> "未知操作";
};
logArea.append("執行: " + desc + NL);
logArea.setCaretPosition(logArea.getDocument().getLength());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("ToolBarDemo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new ToolBarDemo());
f.pack();
f.setVisible(true);
});
}
}
| 特性 | 實現方式 |
|---|---|
| 可拖拽浮動 | JToolBar.setFloatable(true),用戶可拖動邊緣脫離停靠區 |
| 圖標優雅降級 | 資源缺失時自動顯示文本,控制台輸出警告不拋異常 |
| 動作命令模式 | setActionCommand 解耦按鈕與業務邏輯,便於國際化與測試 |
| 工具提示 | setToolTipText 懸停顯示,提升可發現性 |
將按鈕屬性封裝為 AbstractAction,實現菜單項、工具欄按鈕、鍵盤綁定三位一體:
Action openAction = new AbstractAction("打開", new ImageIcon(...)) {
@Override public void actionPerformed(ActionEvent e) { /* 打開邏輯 */ }
};
openAction.putValue(Action.SHORT_DESCRIPTION, "打開文件");
openAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl O"));
JMenuItem menuItem = new JMenuItem(openAction);
JButton toolBtn = new JButton(openAction);
inputMap.put(KeyStroke.getKeyStroke("ctrl O"), "open");
actionMap.put("open", openAction);
JavaFX ToolBar + Button 結合 FontAwesome/Material Icons 字體圖標,無需外部圖片文件,支持 CSS 樣式統一風格。