首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java JToolBar 工具列完整構建:導航按鈕、圖示載入、工具提示與動作事件分發

     編輯:Java 相關知識

構建一個標準的應用程式工具列,包含「開啟」、「儲存」、「搜尋」三個導航按鈕,展示 JToolBar 佈局、按鈕圖示載入(支援優雅降級)、工具提示、動作命令模式與事件集中分發,附帶文字區顯示操作回饋,可直接作為專案工具列基礎模組。

核心類別:ToolBarDemo


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);
        });
    }
}

JToolBar 核心特性速查

特性說明關鍵方法
可拖曳浮動使用者可拖曳工具列脫離成獨立視窗setFloatable(true/false)
方向切換水平/垂直佈局setOrientation(HORIZONTAL/VERTICAL)
分隔線按鈕群組視覺分隔addSeparator(), addSeparator(Dimension)
邊界控制工具列內部邊距setBorder(BorderFactory.createEmptyBorder(...))
滾動支援按鈕過多時自動捲動需放入 JScrollPane 或設定 setLayout(new BoxLayout(...))

圖示載入最佳實踐

  1. 資源路徑**:Class.getResource("/images/icon.gif")(絕對路徑)或 Class.getResource("images/icon.gif")(相對類別包路徑)。
  2. 優雅降級**:圖示缺失時自動顯示文字標籤(altText),避免空白按鈕。
  3. 高解析度支援**:準備 16x16、24x24、32x32 多種尺寸,根據 UIManager.getIcon("OptionPane.informationIcon") 等標準尺寸動態選擇。
  4. 圖示快取**:共用 ImageIcon 實例避免重複載入。

動作命令模式優勢

  • 按鈕、選單項、快捷鍵共用同一 ActionCommand,邏輯集中在 actionPerformed()。
  • 易於擴展:新增功能只需定義新命令字串、建立按鈕/選單項、在 switch 中新增 case。
  • 支援國際化:命令字串固定,顯示文字從資源包讀取。

進階擴展:使用 Action 介面


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);
// 按鈕、選單、工具列、快捷鍵自動同步啟用/停用、圖示、文字、提示
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved