FileDocCategorySizeDatePackage
GrayScalePanel.javaAPI DocExample2636Thu Oct 24 20:14:24 BST 2002None

GrayScalePanel

public class GrayScalePanel extends AbstractColorChooserPanel implements ActionListener, ChangeListener

Fields Summary
JSlider
scale
JTextField
percentField
static Color[]
grays
Constructors Summary
public GrayScalePanel()

   
    for (int i=0; i<256; i++) { grays[i] = new Color(i, i, i); }
  
    setLayout(new GridLayout(0, 1));

    // create the slider and attach us as a listener
    scale = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
    scale.addChangeListener(this);

    // Set up our display for the chooser
    add(new JLabel("Pick your shade of gray:", JLabel.CENTER));
    JPanel jp = new JPanel();
    jp.add(new JLabel("Black"));
    jp.add(scale);
    jp.add(new JLabel("White"));
    add(jp);

    JPanel jp2 = new JPanel();
    percentField = new JTextField(3);
    percentField.setHorizontalAlignment(SwingConstants.RIGHT);
    percentField.addActionListener(this);
    jp2.add(percentField);
    jp2.add(new JLabel("%"));
    add(jp2);
  
Methods Summary
public voidactionPerformed(java.awt.event.ActionEvent ae)

    int val = 100 - Integer.parseInt(ae.getActionCommand());
    getColorSelectionModel().setSelectedColor(grays[(int)(val * 2.55)]);
  
protected voidbuildChooser()

 
public java.lang.StringgetDisplayName()

 return "Gray Scale"; 
public javax.swing.IcongetLargeDisplayIcon()

 return null; 
public javax.swing.IcongetSmallDisplayIcon()

 return null; 
public voidstateChanged(javax.swing.event.ChangeEvent ce)

    getColorSelectionModel().setSelectedColor(grays[scale.getValue()]);
    percentField.setText("" + (100-(int)Math.round(scale.getValue() / 2.55)));
  
protected inttoGray(java.awt.Color c)

    int r = c.getRed();
    int g = c.getGreen();
    int b = c.getBlue();
    // Grab the luminance the same way GIMP does...
    return (int)Math.round(0.3 * r + 0.59 * g + 0.11 * b );
  
public voidupdateChooser()

 
    Color c = getColorSelectionModel().getSelectedColor();
    scale.setValue(toGray(c));