構建一個標準的應用程式工具列,包含「開啟」、「儲存」、「搜尋」三個導航按鈕,展示 JToolBar 佈局、按鈕圖示載入(支援優雅降級)、工具提示、動作命令模式與事件集中分發,附帶文字區顯示操作回饋,可直接作為專案工具列基礎模組。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
public class ToolBarDemo extends JPanel implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final String OPEN = "OPEN", SAVE = "SAVE", SEARCH = "SEARCH";
public ToolBarDemo() {
super(new BorderLayout());
// 建立工具列
JToolBar toolBar = new JToolBar();
addButtons(toolBar);
// 文字區顯示操作日誌
textArea = new JTextArea(15, 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) {
toolBar.add(makeNavigationButton("Open16", OPEN, "開啟一個檔案!", "開啟"));
toolBar.add(makeNavigationButton("Save16", SAVE, "儲存目前檔案!", "儲存"));
toolBar.add(makeNavigationButton("Search16", SEARCH, "搜尋檔案中的字元!", "搜尋"));
}
// 按鈕工廠方法
protected JButton makeNavigationButton(String imageName, String actionCommand, String toolTipText, String altText) {
String imgLocation = "images/" + imageName + ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) {
button.setIcon(new ImageIcon(imageURL));
} else {
button.setText(altText); // 圖示缺失時顯示文字
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
// 事件集中分發
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String desc = switch (cmd) {
case OPEN -> "開啟檔案操作!";
case SAVE -> "儲存檔案操作";
case SEARCH -> "搜尋字元操作";
default -> "未知操作";
};
displayResult("若為真實程式,你將進入:" + desc);
}
protected void displayResult(String msg) { textArea.append(msg + newline); }
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("JToolBar Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ToolBarDemo());
frame.pack();
frame.setVisible(true);
});
}
}
| 特性 | 說明 | 關鍵方法 |
|---|---|---|
| 可拖曳浮動 | 使用者可拖曳工具列脫離成獨立視窗 | setFloatable(true/false) |
| 方向切換 | 水平/垂直佈局 | setOrientation(HORIZONTAL/VERTICAL) |
| 分隔線 | 按鈕群組視覺分隔 | addSeparator(), addSeparator(Dimension) |
| 邊界控制 | 工具列內部邊距 | setBorder(BorderFactory.createEmptyBorder(...)) |
| 滾動支援 | 按鈕過多時自動捲動 | 需放入 JScrollPane 或設定 setLayout(new BoxLayout(...)) |
Class.getResource("/images/icon.gif")(絕對路徑)或 Class.getResource("images/icon.gif")(相對類別包路徑)。altText),避免空白按鈕。UIManager.getIcon("OptionPane.informationIcon") 等標準尺寸動態選擇。ImageIcon 實例避免重複載入。ActionCommand,邏輯集中在 actionPerformed()。
Action openAction = new AbstractAction("開啟", new ImageIcon(openURL)) {
public void actionPerformed(ActionEvent e) { /* 開啟邏輯 */ }
};
openAction.putValue(Action.SHORT_DESCRIPTION, "開啟檔案 (Ctrl+O)");
openAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
JButton openBtn = new JButton(openAction);
JMenuItem openMenu = new JMenuItem(openAction);
// 按鈕、選單、工具列、快捷鍵自動同步啟用/停用、圖示、文字、提示