9.7.5 颜色选择器 作用:可通过调色板选择颜色 显示: Color selectedColor = JColorChooser.showDialog(parent, title, initialColor); import javax . swing . * ; import javax . swing . event . ChangeEvent ; import javax . swin
9.7.5 颜色选择器
作用:可通过调色板选择颜色
显示:
Color selectedColor = JColorChooser.showDialog(parent, title, initialColor);
import javax.swing.*;import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
Main solution = new Main();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ColorChooserFrame ColorChooserFrame = new ColorChooserFrame();
ColorChooserFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorChooserFrame.setVisible(true);
}
});
}
}
class ColorChooserFrame extends JFrame {
public static final int W = 600;
public static final int H = 400;
public ColorChooserFrame(){
setTitle("ColorChooserTest");
setSize(W,H);
ColorChooserPanel panel = new ColorChooserPanel();
add(panel);
}
class ColorChooserPanel extends JPanel{
public ColorChooserPanel(){
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener());
add(modalButton);
JButton modelessButton = new JButton("Modeless");
modelessButton.addActionListener(new ModelessListener());
add(modelessButton);
JButton immediateButton = new JButton("Immediate");
immediateButton.addActionListener(new ImmediateListener());
add(immediateButton);
}
private class ModalListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Color defaultColor = getBackground();
Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
defaultColor);
if(selected != null) setBackground(selected);
}
}
private class ModelessListener implements ActionListener{
private JDialog dialog;
private JColorChooser chooser;
public ModelessListener(){
chooser = new JColorChooser();
dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color", false,
chooser, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setBackground(chooser.getColor());
}
},null);
}
@Override
public void actionPerformed(ActionEvent e) {
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
private class ImmediateListener implements ActionListener{
private JDialog dialog;
private JColorChooser chooser;
public ImmediateListener(){
chooser = new JColorChooser();
chooser.getSelectionModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setBackground(chooser.getColor());
}
});
dialog = new JDialog((Frame) null, false);
dialog.add(chooser);
dialog.pack();
}
@Override
public void actionPerformed(ActionEvent e) {
chooser.setColor(getBackground());
dialog.setVisible(true);
}
}
}
}
三个按钮对应的是:模式框、非模式框、非模式立刻更新页面三种
可选各种颜色更新背景
PS:昨天的内容忘记发了T T, 已追加到 (15)
相关内容:选择 《Java核心技术 卷1》查找相关笔记
喜欢的话,点个赞吧~!平时做题,以及笔记内容将更新到公众号。