Keyboard inputTopMore Panels and GUI Components

More Panels and GUI Components

Suppose we want to be able to select any color at all for the geometric objects. Thus we need to make a color out of three components, each of which is in the range from 0 to 255. We can accomplish this by adding three sliders to our window.

For simplicity, we create a simpler application that just has a filled rectangle filling the canvas that will be set to be the color set by the three sliders. JSliders are similar to JComboBoxes and JButtons. The constructor is written in the form:

      redSlider = new JSlider(orientation,MIN_VALUE, MAX_VALUE, STARTING_VALUE);

where orientation is either JSlider.HORIZONTAL or JSlider.VERTICAL, and the next three integer values provide the smallest and largest values represented by the JSlider and the starting position of the JSlider (somewhere between the min and max values). JSliders use ChangeListeners, so we write

									
      redSlider.addChangeListener(this);

the class implements ChangeListener, and the event-handling method is

									
      public void stateChanged(ChangeEvent evt) {...}

See the ColorSlider example.

Notice that we can obtain the integer value represented by the slider by evaluating redSlider.getValue(), which always returns an int.

We have made this example more readable by adding labels on both sides of each slider. The label on the left indicates what the slider represents, while the label on the right indicates the current value of the slider. Both are created using JLabel. JLabels are normally centered, but we can change the justification by adding a second parameter of JLabel.RIGHT or JLabel.LEFT (the first parameter is the initial text showing on the label). The text on a label can be changed using the setText method of JLabel.

Question: What is the difference between a Text item and a JLabel? (Hint: the difference is where they can occur and how you specify their locations.)


Keyboard inputTopMore Panels and GUI Components