Swing 提供 JColorChooser 讓使用者透過對話框選取顏色。本文示範一個簡單視窗,點擊按鈕開啟選色器,並將選取顏色套用至標籤文字。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserDemo extends JFrame {
private JLabel sampleText = new JLabel("示範文字");
private JButton chooseButton = new JButton("選擇顏色");
public ColorChooserDemo() {
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(sampleText);
panel.add(chooseButton);
add(panel);
chooseButton.addActionListener(e -> {
Color c = JColorChooser.showDialog(this, "選擇顏色", sampleText.getForeground());
if (c != null) sampleText.setForeground(c);
});
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ColorChooserDemo::new);
}
}
JColorChooser.showDialog 為靜態便利方法,回傳使用者選取的 Color 或 null(取消)。