package paint;
/*
* ColorChooserDemo.java
*/
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class ColorChooserDemo extends JFrame implements ChangeListener, ListSelectionListener {
final private JColorChooser colorChooser;
final private JTable colorBoxes;
final private JPanel colorBoxesPanel;
final private int BOX_W = 80;
final private int BOX_H = 100;
final private Color[] initialColors = new Color[]{Color.red, Color.green, Color.blue};
public ColorChooserDemo() {
super("Color Chooser Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(530,330);
setLocationRelativeTo(null);
colorBoxes = new JTable();
colorBoxes.setRowHeight(BOX_H);
DefaultTableModel model = new DefaultTableModel(initialColors.length,1){
public Class getColumnClass(final int columnIndex) {return Icon.class;}
};
for (int i = 0; i < initialColors.length; i++)
model.setValueAt( new MyIcon(initialColors[i], new Dimension(BOX_W, BOX_H)), i, 0 );
colorBoxes.setModel(model);
colorBoxes.setTableHeader(null);
colorBoxes.changeSelection(0,0,false,false);
colorBoxes.getSelectionModel().addListSelectionListener(this);
colorBoxesPanel = new JPanel(new BorderLayout());
colorBoxesPanel.setPreferredSize(new Dimension(BOX_W, BOX_H));
colorBoxesPanel.add(new JScrollPane(colorBoxes));
add(colorBoxesPanel, BorderLayout.WEST);
colorChooser = new JColorChooser( ((MyIcon)colorBoxes.getValueAt(
colorBoxes.getSelectedRow(), 0)).getColor() );
colorChooser.getSelectionModel().addChangeListener(this); //<-----------------
add(colorChooser, BorderLayout.EAST);
}
public void stateChanged(final ChangeEvent e) { //<-------------------------------
Color newColor = colorChooser.getColor();
((MyIcon)colorBoxes.getValueAt(colorBoxes.getSelectedRow(), 0)).setColor(newColor);
colorBoxes.repaint();
}
public static void main(final String[] args) {new ColorChooserDemo().setVisible(true);}
public void valueChanged(ListSelectionEvent e) {
colorChooser.setColor( ((MyIcon)colorBoxes.getValueAt(
colorBoxes.getSelectedRow(), 0)).getColor() );
}
}
class MyIcon implements Icon {
private Color color;
final private Dimension size;
public MyIcon(final Color color, final Dimension size) {
this.color = color;
this.size = size;
}
public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
g.setColor(color);
g.fillRect(0,0,getIconWidth(), getIconHeight());
g.setColor(Color.black);
g.fillRect(0,0,getIconWidth(), 13);
g.setColor(Color.white);
g.drawString(color.getRed()+","+color.getGreen()+","+color.getBlue(),1,11);
}
public int getIconWidth() {return size.width;}
public int getIconHeight() {return size.height;}
public Color getColor(){return color;}
public void setColor(final Color newColor) {color = newColor;}
}