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

[Java GUI 範例] JTabbedPane 選項卡完整演示

     編輯:Java 相關知識

程式功能

展示 Swing JTabbedPane 基本用法:建立四個分頁,每個分頁顯示不同文字內容,並設定圖示與工具提示。

完整代碼

import javax.swing.*;
import java.awt.*;

public class TabbedPaneDemo extends JPanel {
    public TabbedPaneDemo() {
        super(new GridLayout(1, 1));
        ImageIcon icon = createImageIcon("images/middle.gif");
        JTabbedPane tabbedPane = new JTabbedPane();

        tabbedPane.addTab("One", icon, makeTextPanel("#第一個卡片#"), "第一個卡片提示信息!");
        tabbedPane.setSelectedIndex(0);
        tabbedPane.addTab("Two", icon, makeTextPanel("##第二個卡片##"), "第二個卡片提示信息!");
        tabbedPane.addTab("Three", icon, makeTextPanel("###第三個卡片###"), "第三個卡片提示信息!");
        tabbedPane.addTab("Four", icon, makeTextPanel("####第四個卡片####"), "第四個卡片提示信息!");

        add(tabbedPane);
    }

    protected Component makeTextPanel(String text) {
        JPanel panel = new JPanel(false);
        JLabel filler = new JLabel(text);
        filler.setHorizontalAlignment(JLabel.CENTER);
        panel.setLayout(new GridLayout(1, 1));
        panel.add(filler);
        return panel;
    }

    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = TabbedPaneDemo.class.getResource(path);
        if (imgURL != null) return new ImageIcon(imgURL);
        System.err.println("Couldn't find file: " + path);
        return null;
    }

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("TabbedPaneDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TabbedPaneDemo(), BorderLayout.CENTER);
        frame.setSize(400, 200);
        frame.setVisible(true);
    }
}

關鍵點解析

  • addTab(title, icon, component, toolTip) 一次性設定標題、圖示、內容面板、懸停提示。
  • setSelectedIndex(0) 指定預設顯示第一個分頁。
  • 使用 Class.getResource() 載入圖片,支援打包成 JAR 後仍能正確讀取。
  • 主程式啟用 JFrame.setDefaultLookAndFeelDecorated(true) 使用系統原生視窗裝飾。

執行效果

視窗頂部顯示四個分頁標籤(One~Four),點擊切換下方內容,滑鼠懸停顯示對應提示文字。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved