• Post Reply Bookmark Topic Watch Topic
  • New Topic

getting values from change listener  RSS feed

Steven Coddington
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a beginner and just learning to use swing widgets. I want to make a color maker to see what various rgb combos look like. I want three sliders, with values from 0-255, get the values, and re-color a region so I can see the effect. I have the sliders working, but don't know how to get the value from the change listener to the panel drawer. Here is what I have so far.

Any help is greatly appreciated. Thanks.

* SliderTest.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Container;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JSlider;
import javax.swing.event.*;

public class SliderTest extends JFrame{
// Declare class variables
JFrame frame;
JLabel label;

// Creates a new instance of SliderTest
public static void main(String[] args) {
SliderTest gui = new SliderTest();

// Build a gui
public void go() {
frame = new JFrame();

JButton colorButton = new JButton("Change Circle");

// Add three sliders to the a container

Container sliderContainer = getContentPane();
sliderContainer.setLayout(new GridLayout(3,1));

JSlider redSlider = new JSlider(0,0,255,127);
JSlider greenSlider = new JSlider(0,0,255,127);
JSlider blueSlider = new JSlider(0,0,255,127);

redSlider.addChangeListener(new RedChangeListener());


MyDrawPanel drawPanel= new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.NORTH, sliderContainer);


// An inner class for the slider event
class RedChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent e){
JSlider redSource = (JSlider)e.getSource();
if (!redSource.getValueIsAdjusting()) {
redValue = (int)redSource.getValue();
System.out.println (redValue);

// Make the Draw Panel an inner class
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {

int redValue = 127; /* This is where I would like to put the value from the slider.
int greenValue = 127;
int blueValue = 127;
Color newColor = new Color(redValue, greenValue, blueValue);

//erase old oval by repainting rectangle
g.fillRect(0, 0, this.getWidth(), this.getHeight());

g.fillOval(70, 70, 100, 100);
public void stateChanged(javax.swing.event.ChangeEvent changeEvent) {

Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
maybe something like this

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!