In this section, you will learn how to create sliders to show RGB colors.
In this section, you will learn how to create sliders to show RGB colors.JSlider with RGB Colors
In this section, you will learn how to create sliders to show RGB colors.
In this example, we have created three horizontal sliders, first one as red, the second one as green and the third one as blue. It lets the user to set the red, green, and blue levels in a color by manipulating sliders.The JPanel component is used in a code to allow the user to specify the drawing color.
Example:
import java.awt.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.basic.*; class Slider extends JSlider{ private String type; private RangeSlider ui; public Slider(int min, int max, String type){ super(min, max); this.type = type; } public void updateUI(){ ui = new RangeSlider(this); setUI(ui); updateLabelUIs(); } public RangeSlider getUI(){ return ui; } public String getType(){ return type; } } class RangeSlider extends BasicSliderUI{ public Color[] gradient = new Color[256]; public RangeSlider(JSlider B){ super(B); } public void updateGradient(int othercolor, int othercolor2){ if ("Red".equals(((Slider) slider).getType())){ for(int i = 0; i < gradient.length; i++){ gradient[i] = new Color(i, othercolor, othercolor2); } } if ("Green".equals(((Slider) slider).getType())){ for (int i = 0; i < gradient.length; i++){ gradient[i] = new Color(othercolor, i, othercolor2); } } if ("Blue".equals(((Slider) slider).getType())){ for (int i = 0; i < gradient.length; i++){ gradient[i] = new Color(othercolor, othercolor2, i); } } slider.repaint(); } } public class ColorSlider extends JFrame implements ChangeListener{ Slider redSlider = new Slider(0, 255, "Red"); Slider greenSlider = new Slider(0, 255, "Green"); Slider blueSlider = new Slider(0, 255, "Blue"); JPanel colourDisplay = new JPanel(); public ColorSlider(){ setVisible(true); setSize(300, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new GridLayout(4, 1)); redSlider.addChangeListener(this); greenSlider.addChangeListener(this); blueSlider.addChangeListener(this); add(redSlider); add(greenSlider); add(blueSlider); add(colourDisplay); } public void stateChanged(ChangeEvent e){ int red = redSlider.getValue(); int green = greenSlider.getValue(); int blue = blueSlider.getValue(); redSlider.getUI().updateGradient(green, blue); greenSlider.getUI().updateGradient(red, blue); blueSlider.getUI().updateGradient(red, green); this.colourDisplay.setBackground(new Color(red, green, blue)); } public static void main(String[] args){ new ColorSlider(); } }
Output: