第16章 选取器
本章介绍两个Swing选取器组件,它们是:JFileChooser和JColorChooser,它们分别用于选取文件和颜色。
16.1 JFileChooser
文件选取器(与选项窗格一样,参见14.3节“JOptionPane”)是放置在对话框中的轻量组件。一旦创建了一个JFileChooser实例,就可以把这个实例添加到一个对话框中。而且,JFileChooser类还提供了一些方法,这些方法把已存在的文件添加到一个模态对话框中。并且显示这个对话框。这些方法返回一个integer值,指出是激活了选取器的批准按钮还是清除了这个对话框。
文件选取器支持三种显示模式:只显示文件、只显示目录和显示文件及目录。另外,文件选取器还支持单文件选取和多文件选取(Swing1.1FCS不完全支持多文件选取。)
可以用许多不同的方法来定制文件选取器,如图16-1所示。图16-1中的上图显示调用JFileChooser.showSaveDialog()后显示的标准对话框。图16-1
例子 16-1 一个简单的文件选取器例子
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.beans.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
JButton button = new JButton("show file chooser ...");
public Test() {
super("Simple File Chooser Application");
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int state = chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
if(file != null &&
state == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(
null, file.getPath());
}
else if(state == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(
null, "Canceled");
}
else if(state == JFileChooser.ERROR_OPTION) {
JOptionPane.showMessageDialog(
null, "Error!");
}
}
});
}
public static void main(String args[]) {
JFrame f = new Test();
f.setBounds(300,300,350,100);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
16.1.1 文件选取器类型
例子 16-2 缺省的文件选取器类型
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
JComboBox comboBox = new JComboBox();
JButton button = new JButton("show file chooser ...");
public Test() {
super("Standard File Chooser Types");
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(comboBox);
contentPane.add(button);
comboBox.addItem("OPEN_DIALOG");
comboBox.addItem("SAVE_DIALOG");
comboBox.addItem("custom dialog");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message = "CANCELED";
int state = showChooser(
(String)comboBox.getSelectedItem());
File file = chooser.getSelectedFile();
if(file != null &&
state == JFileChooser.APPROVE_OPTION) {
message = chooser.getApproveButtonText() +
" " + file.getPath();
}
JOptionPane.showMessageDialog(null, message);
}
});
}
private int showChooser(String s) {
int state;
if(s.equals("OPEN_DIALOG")) {
state = chooser.showOpenDialog(null);
}
else if(s.equals("SAVE_DIALOG")) {
state = chooser.showSaveDialog(null);
}
else { // custom dialog
String string = JOptionPane.showInputDialog(
null,
"Button/Title String:");
chooser.setApproveButtonMnemonic(string.charAt(1));
state = chooser.showDialog(Test.this, string);
}
return state;
}
public static void main(String args[]) {
JFrame f = new Test();
f.setBounds(300,300,350,100);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
16.1.2 可访问组件
例子 16-3 一个图像预览器可访问组件
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
ImagePreviewer previewer = new ImagePreviewer();
public Test() {
super("Accessory Components");
Container contentPane = getContentPane();
JButton button = new JButton("Select A File");
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
setAccessoryComponent();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooser.showOpenDialog(null);
}
});
}
private void setAccessoryComponent() {
JPanel previewPanel = new JPanel();
previewPanel.setLayout(new BorderLayout());
previewPanel.add(new JLabel("Image Previewer",
SwingConstants.CENTER),
BorderLayout.NORTH);
previewPanel.add(previewer, BorderLayout.CENTER);
previewer.setPreferredSize(new Dimension(200,0));
previewer.setBorder(BorderFactory.createEtchedBorder());
chooser.setAccessory(previewPanel);
new ImagePreviewerAccessoryAdapter(chooser, previewer);
}
public static void main(String a[]) {
JFrame f = new Test();
f.setBounds(300, 300, 300, 75);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
class ImagePreviewerAccessoryAdapter extends Object {
public ImagePreviewerAccessoryAdapter(
JFileChooser chooser,
final ImagePreviewer previewer) {
chooser.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals(
JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
previewer.update((File)e.getNewValue());
}
}
});
}
}
class ImagePreviewer extends JComponent {
private ImageIcon icon;
public void update(File file) {
Dimension size = getSize();
Insets insets = getInsets();
icon = new ImageIcon(file.getPath());
icon.setImage(icon.getImage().getScaledInstance(
size.width - insets.left - insets.right,
size.height - insets.top - insets.bottom,
Image.SCALE_SMOOTH));
if(isShowing()) {
repaint();
}
}
public void paintComponent(Graphics g) {
Insets insets = getInsets();
super.paintComponent(g);
if(icon != null)
icon.paintIcon(this, g, insets.left, insets.top);
}
}
16.1.3 过滤文件类型
例子 16-4 一个文本文件过滤器和预览器
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.util.*;
import java.net.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
TextPreviewer previewer = new TextPreviewer();
JPanel previewPanel = new PreviewPanel();
class PreviewPanel extends JPanel {
public PreviewPanel() {
JLabel label = new JLabel("Text Previewer",
SwingConstants.CENTER);
setPreferredSize(new Dimension(250,0));
setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
label.setBorder(BorderFactory.createEtchedBorder());
add(label, BorderLayout.NORTH);
add(previewer, BorderLayout.CENTER);
}
}
public Test() {
super("Accessory Components");
Container contentPane = getContentPane();
JButton button = new JButton("Select A File");
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
chooser.setAccessory(previewPanel);
chooser.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals(
JFileChooser.SELECTED_FILE_CHANGED_PROPERTY))
previewer.update((File)e.getNewValue());
}
});
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooser.showOpenDialog(null);
}
});
}
public static void main(String a[]) {
JFrame f = new Test();
f.setBounds(300, 300, 300, 75);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
class TextPreviewer extends JComponent {
private ImageIcon icon;
private JTextArea textArea = new JTextArea();
public TextPreviewer() {
setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
public void update(File file) {
textArea.setText(contentsOfFile(file));
if(isShowing()) {
textArea.revalidate();
}
}
static String contentsOfFile(File file) {
String s = new String();
char[] buff = new char[50000];
InputStream is;
InputStreamReader reader;
URL url;
try {
reader = new FileReader(file);
int nch;
while ((
nch = reader.read(buff, 0, buff.length)) != -1) {
s = s + new String(buff, 0, nch);
}
}
catch (java.io.IOException ex) {
s = "Could not load file";
}
return s;
}
}
例子 16-5 多种文件过滤器
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.net.URL;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
TextPreviewer previewer = new TextPreviewer();
PreviewPanel previewPanel = new PreviewPanel();
class PreviewPanel extends JPanel {
public PreviewPanel() {
JLabel label = new JLabel("Text Previewer",
SwingConstants.CENTER);
setPreferredSize(new Dimension(350,0));
setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
label.setBorder(BorderFactory.createEtchedBorder());
add(label, BorderLayout.NORTH);
add(previewer, BorderLayout.CENTER);
}
}
public Test() {
super("Filtering Files");
Container contentPane = getContentPane();
JButton button = new JButton("Select A File");
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int state = chooser.showOpenDialog(null);
String s = "CANCELED";
if(state == JFileChooser.APPROVE_OPTION) {
s = "File Selected: " +
chooser.getSelectedFile().getPath();
}
JOptionPane.showMessageDialog(null, s);
}
});
chooser.setAccessory(previewPanel);
chooser.addChoosableFileFilter(new TextFilter());
chooser.addChoosableFileFilter(new JavaCodeFilter());
chooser.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals(
JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
previewer.configure((File)e.getNewValue());
}
}
});
}
public static void main(String a[]) {
JFrame f = new Test();
f.setBounds(300, 300, 300, 75);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
abstract class SuffixAwareFilter
extends javax.swing.filechooser.FileFilter {
public String getSuffix(File f) {
String s = f.getPath(), suffix = null;
int i = s.lastIndexOf('.');
if(i > 0 && i < s.length() - 1)
suffix = s.substring(i+1).toLowerCase();
return suffix;
}
public boolean accept(File f) {
return f.isDirectory();
}
}
class ImageFilter extends SuffixAwareFilter {
public boolean accept(File f) {
boolean accept = super.accept(f);
if( ! accept) {
String suffix = getSuffix(f);
if(suffix != null)
accept = super.accept(f) || suffix.equals("jpg")
|| suffix.equals("gif");
}
return accept;
}
public String getDescription() {
return "Java Source Code Files(*.java)";
}
}
class JavaCodeFilter extends SuffixAwareFilter {
public boolean accept(File f) {
boolean accept = super.accept(f);
if( ! accept) {
String suffix = getSuffix(f);
if(suffix != null)
accept = super.accept(f) || suffix.equals("java");
}
return accept;
}
public String getDescription() {
return "Java Source Code Files(*.java)";
}
}
class TextFilter extends SuffixAwareFilter {
public boolean accept(File f) {
String suffix = getSuffix(f);
if(suffix != null)
return super.accept(f) || suffix.equals("txt");
return false;
}
public String getDescription() {
return "Text Files(*.txt)";
}
}
class TextPreviewer extends JComponent {
private JTextArea textArea = new JTextArea();
private JScrollPane scrollPane = new JScrollPane(textArea);
public TextPreviewer() {
textArea.setEditable(false);
setBorder(BorderFactory.createEtchedBorder());
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
public void configure(File file) {
textArea.setText(contentsOfFile(file));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JViewport vp = scrollPane.getViewport();
vp.setViewPosition(new Point(0,0));
}
});
}
static String contentsOfFile(File file) {
String s = new String();
char[] buff = new char[50000];
InputStream is;
InputStreamReader reader;
URL url;
try {
reader = new FileReader(file);
int nch;
while ((
nch = reader.read(buff, 0, buff.length)) != -1) {
s = s + new String(buff, 0, nch);
}
}
catch (java.io.IOException ex) {
s = "Could not load file";
}
return s;
}
}
16.1.4 文件视图
例子 16-6 一个定制的文件视图
import javax.swing.*;
import javax.swing.filechooser.FileView;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
JButton button = new JButton("show file chooser ...");
public Test() {
super("Custom File View Example");
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
chooser.setFileView(new CustomFileView());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int state = chooser.showSaveDialog(null);
File file = chooser.getSelectedFile();
String s = "CANCELED";
if(state == JFileChooser.APPROVE_OPTION)
s = "File: " + file.getPath();
JOptionPane.showMessageDialog(null, s);
}
});
}
public static void main(String args[]) {
JFrame f = new Test();
f.setBounds(300,300,350,100);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
class CustomFileView extends FileView {
private Icon fileIcon = new ImageIcon("file.gif"),
directoryIcon = new ImageIcon("folder.gif"),
imageIcon = new ImageIcon("photo.jpg");
public String getName(File f) { return null; }
public String getDescription(File f) { return null; }
public String getTypeDescription(File f) { return null; }
public Icon getIcon(File f) {
Icon icon = null;
if(isImage(f)) icon = imageIcon;
else if(f.isDirectory()) icon = directoryIcon;
else icon = fileIcon;
return icon;
}
public Boolean isTraversable(File f) {
Boolean b = null;
if(f.getPath().equals("D://file.txt")) {
b = new Boolean(false);
}
else if(f.getPath().equals("D://books")) {
b = new Boolean(false);
}
return b == null ? new Boolean(true) : b;
}
private boolean isImage(File f) {
String suffix = getSuffix(f);
boolean isImage = false;
if(suffix != null) {
isImage = suffix.equals("gif") ||
suffix.equals("bmp") ||
suffix.equals("jpg");
}
return isImage;
}
private String getSuffix(File file) {
String filestr = file.getPath(), suffix = null;
int i = filestr.lastIndexOf('.');
if(i > 0 && i < filestr.length()) {
suffix = filestr.substring(i+1).toLowerCase();
}
return suffix;
}
}
16.1.5 多文件选取
例子 16-7 文件选取器的多文件选取
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import java.beans.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
JButton button = new JButton("show file chooser ...");
public Test() {
super("Simple File Chooser Application");
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
chooser.setMultiSelectionEnabled(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int state = chooser.showOpenDialog(null);
File[] files = chooser.getSelectedFiles();
String[] filenames = getFilenames(files);
if(filenames != null &&
state == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null,filenames);
}
else if(state == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(
null, "Canceled");
}
else if(state == JFileChooser.ERROR_OPTION) {
JOptionPane.showMessageDialog(
null, "Error!");
}
}
});
}
private String[] getFilenames(File[] files) {
String[] filenames = null;
int numFiles = files.length;
System.out.println(numFiles);
if(files.length > 0) {
filenames = new String[numFiles];
for(int i=0; i < numFiles; ++i) {
filenames[i] = files[i].getPath();
System.out.println(filenames[i]);
}
}
return filenames;
}
public static void main(String args[]) {
JFrame f = new Test();
f.setBounds(300,300,350,100);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
16.1.6 JFileChooser属性
16.1.7 JFileChooser事件
例子 16-8 JFileChooser动作事件
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
public class Test extends JFrame {
JFileChooser chooser = new JFileChooser();
JDialog dialog;
JButton button = new JButton("show file chooser ...");
public Test() {
super("Simple File Chooser Application");
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title = chooser.getDialogTitle();
if(title == null)
chooser.getUI().getDialogTitle(chooser);
dialog = new JDialog((Frame)null, title, false);
Container dialogContentPane =
dialog.getContentPane();
dialogContentPane.setLayout(new BorderLayout());
dialogContentPane.add(chooser,
BorderLayout.CENTER);
dialog.setTitle("Non-Modal File Chooser");
dialog.pack();
dialog.setLocationRelativeTo(Test.this);
dialog.setVisible(true);
}
});
chooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String state = (String)e.getActionCommand();
if(state.equals(JFileChooser.APPROVE_SELECTION)) {
File file = chooser.getSelectedFile();
JOptionPane.showMessageDialog(
null, file.getPath());
}
else if(
state.equals(JFileChooser.CANCEL_SELECTION)) {
JOptionPane.showMessageDialog(
null, "Canceled");
}
// JFileChooser action listeners are notified
// when one either the approve button or
// cancel button is activated
dialog.setVisible(false);
}
});
}
public static void main(String args[]) {
JFrame f = new Test();
f.setBounds(300,300,350,100);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}
16.1.8 JFileChooser类总结
16.1.9 AWT兼容
16.2 JColorChooser
例16-9 在一个小应用程序中显示的颜色选取器
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
import java.awt.*;
public class Test extends JApplet {
JColorChooser chooser = new JColorChooser();
ColorSelectionModel model = chooser.getSelectionModel();
public void init() {
getContentPane().add(chooser, BorderLayout.CENTER);
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
showStatus("Color: " + chooser.getColor());
}
});
}
}
16.2.1 在对话框中显示颜色选取器
例16-10 在对话框中显示的颜色选取器
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
public void init() {
getContentPane().add(new Palette(), BorderLayout.CENTER);
}
}
class Palette extends JPanel {
private Color[] defaultColors = new Color[] {
Color.blue, Color.red, Color.yellow, Color.green,
Color.magenta, Color.darkGray, Color.white, Color.orange,
Color.pink, Color.cyan, Color.lightGray, Color.gray,
};
public Palette() {
int columns = 3;
setBorder(
BorderFactory.createTitledBorder("Color Palette"));
setLayout(new GridLayout(columns,0,1,1));
for(int i=0; i < defaultColors.length; ++i)
add(new ColorPatch(defaultColors[i]));
}
}
class ColorPatch extends JPanel {
JApplet applet;
Color selectedColor;
public ColorPatch(Color color) {
setBorder(BorderFactory.createEtchedBorder());
setBackground(color);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
selectedColor = JColorChooser.showDialog(
ColorPatch.this, // parent comp
"Pick A Color", // dialog title
getBackground()); // initial color
if(selectedColor == null) {
JOptionPane.showMessageDialog(ColorPatch.this,
"ColorChooser Canceled");
}
else {
setBackground(selectedColor);
repaint();
JOptionPane.showMessageDialog(ColorPatch.this,
"Color Selected: " + selectedColor);
}
}
});
}
}
16.2.2 定制颜色选取器
例16-11 颜色选取器中的一个定制预览
import javax.swing.*;
import javax.swing.colorchooser.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
private JColorChooser chooser = new JColorChooser();
private JButton button = new JButton("Show Color Chooser");
private JDialog dialog;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button, BorderLayout.CENTER);
chooser.setPreviewPanel(new PreviewPanel());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(dialog == null)
dialog = JColorChooser.createDialog(
Test.this, // parent comp
"Pick A Color", // dialog title
false, // modality
chooser,
null, null);
dialog.setVisible(true);
}
});
}
class PreviewPanel extends JPanel {
public PreviewPanel() {
setPreferredSize(new Dimension(0,100));
setBorder(BorderFactory.createRaisedBevelBorder());
}
public void paintComponent(Graphics g) {
Dimension size = getSize();
g.setColor(getForeground());
g.fillRect(0,0,size.width,size.height);
}
}
}
例16-12 实现一个定制颜色选取器面板
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JApplet {
private JColorChooser chooser = new JColorChooser();
private AbstractColorChooserPanel colorPanels[] =
new AbstractColorChooserPanel[] {
new ListPanel(),
};
private JButton button = new JButton("Show Color Chooser");
private JDialog dialog;
public void init() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button, BorderLayout.CENTER);
chooser.setChooserPanels(colorPanels);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(dialog == null)
dialog = JColorChooser.createDialog(
Test.this, // parent comp
"Pick A Color", // dialog title
false, // modality
chooser,
null, null);
dialog.setVisible(true);
}
});
}
}
class ListPanel extends AbstractColorChooserPanel
implements ListSelectionListener {
private JPanel labelPanel = new JPanel(),
listPanel = new JPanel();
private JList redList = new JList(), blueList = new JList(),
greenList = new JList();
private DefaultListModel redModel = new DefaultListModel(),
blueModel = new DefaultListModel(),
greenModel = new DefaultListModel();
private boolean isAdjusting = false;
public void updateChooser() {
if( ! isAdjusting) {
isAdjusting = true;
Color color = getColorFromModel();
int r = color.getRed(), g = color.getGreen(),
b = color.getBlue();
redList.setSelectedIndex(r);
redList.ensureIndexIsVisible(r);
blueList.setSelectedIndex(b);
blueList.ensureIndexIsVisible(b);
greenList.setSelectedIndex(g);
greenList.ensureIndexIsVisible(g);
isAdjusting = false;
}
}
protected void buildChooser() {
redList.setFixedCellWidth(50);
greenList.setFixedCellWidth(50);
blueList.setFixedCellWidth(50);
for(int i=0; i < 256; ++i) {
redModel.addElement(Integer.toString(i));
greenModel.addElement(Integer.toString(i));
blueModel.addElement(Integer.toString(i));
}
redList.setModel(redModel);
greenList.setModel(greenModel);
blueList.setModel(blueModel);
listPanel.setLayout(new GridLayout(0,3,10,0));
listPanel.add(new JScrollPane(redList));
listPanel.add(new JScrollPane(blueList));
listPanel.add(new JScrollPane(greenList));
labelPanel.setLayout(new GridLayout(0,3,10,0));
labelPanel.add(new JLabel("Red"));
labelPanel.add(new JLabel("Blue"));
labelPanel.add(new JLabel("Green"));
setLayout(new BorderLayout());
add(labelPanel, BorderLayout.NORTH);
add(listPanel, BorderLayout.CENTER);
redList.addListSelectionListener(this);
greenList.addListSelectionListener(this);
blueList.addListSelectionListener(this);
}
public void valueChanged(ListSelectionEvent e) {
int r = redList.getSelectedIndex(),
b = blueList.getSelectedIndex(),
g = greenList.getSelectedIndex();
if(r != -1 && g != -1 && b != -1)
getColorSelectionModel().setSelectedColor(
new Color(r,g,b));
}
public String getDisplayName() {
return "display name";
}
public Icon getSmallDisplayIcon() {
return null;
}
public Icon getLargeDisplayIcon() {
return null;
}
}
16.2.3 JColorChooser属性
16.2.4 JColorChooser事件
16.2.5 JColorChooser类总结
16.2.6 AWT兼容
16.3 本章回顾
略