// ColorSlider.java - originally SliderFrame.java // from text by Cay Horstmann: Java Concepts, 2005. // modified and converted to applet by cmc, 6/3/07 import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import javax.swing.JApplet; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; public class ColorSlider extends JApplet { public ColorSlider() { colorPanel = new JPanel(); add(colorPanel, BorderLayout.CENTER); createControlPanel(); setSampleColor(); } public void createControlPanel() { class ColorListener implements ChangeListener { public void stateChanged(ChangeEvent event) { setSampleColor(); } } ChangeListener listener = new ColorListener(); redSlider = new JSlider(0, 255, 255); redSlider.addChangeListener(listener); greenSlider = new JSlider(0, 255, 175); greenSlider.addChangeListener(listener); blueSlider = new JSlider(0, 255, 175); blueSlider.addChangeListener(listener); JPanel controlPanel = new JPanel(); controlPanel.setLayout(new GridLayout(3, 2)); redLabel = new JLabel("Red: " + 255); controlPanel.add(redLabel); controlPanel.add(redSlider); greenLabel = new JLabel("Green: " + 175); controlPanel.add(greenLabel); controlPanel.add(greenSlider); blueLabel = new JLabel("Blue: " + 175); controlPanel.add(blueLabel); controlPanel.add(blueSlider); add(controlPanel, BorderLayout.SOUTH); } /** Reads the slider values and sets the panel to the selected color. */ public void setSampleColor() { // Read slider values int red = redSlider.getValue(); int green = greenSlider.getValue(); int blue = blueSlider.getValue(); // Set panel background to selected color colorPanel.setBackground(new Color(red, green, blue)); colorPanel.repaint(); // cmc: set label text redLabel.setText(String.format("Red: %d (out of 255)", red)); greenLabel.setText(String.format("Green: %d", green)); blueLabel.setText(String.format("Blue: %d", blue)); } private JPanel colorPanel; private JSlider redSlider; private JSlider greenSlider; private JSlider blueSlider; // cmc: so labels can show levels too private JLabel redLabel; private JLabel greenLabel; private JLabel blueLabel; }