JColorChooser 是 Swing 內建的顏色選擇對話框,提供標準色盤、HSB/RGB 滑桿、自訂色板等功能。本文展示如何整合至應用程式,讓使用者點選按鈕彈出選色器並即時套用至元件前景色。
package com.liuxing.test;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ColorChooserDemo extends JFrame {
private JLabel sampleText = new JLabel("顏色預覽文字");
private JButton chooseButton = new JButton("選擇顏色");
public static void main(String[] args) {
SwingUtilities.invokeLater(ColorChooserDemo::new);
}
public ColorChooserDemo() {
setTitle("JColorChooser 示範");
setSize(350, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel panel = new JPanel();
sampleText.setFont(sampleText.getFont().deriveFont(24f));
panel.add(sampleText);
chooseButton.addActionListener(e -> {
Color initial = sampleText.getForeground();
Color picked = JColorChooser.showDialog(this, "選擇文字顏色", initial);
if (picked != null) {
sampleText.setForeground(picked);
}
});
panel.add(chooseButton);
add(panel);
setVisible(true);
}
}
// 靜態工廠方法,回傳使用者選擇的 Color,取消則回傳 null
Color JColorChooser.showDialog(Component parent, String title, Color initialColor)
new JColorChooser() 可直接加入容器,不以對話框形式彈出chooser.setPreviewPanel(new JPanel()) 可自訂或隱藏預覽區chooser.setDragEnabled(true) 允許拖曳色板排序文字編輯器字型顏色、圖表系列顏色設定、主題皮膚自訂、繪圖工具筆刷顏色選擇等。