Reputation: 16081
I am using the visual design editor in Netbeans. I have two sliders with corresponding JLabels. What I want is a rectangle that changes color when the slider is moved. How do I incorporate this with the designer's generated code?
How do I paint my rectangle near the slider?
Upvotes: 1
Views: 755
Reputation: 1267
Colors in Java are composed by RGB
values.
Color c = new Color(red, green, blue)
Red
, Green
and Blue
all have integer
values between 0 and 255. Netbeans visual editor allows you to set both maximum
and minimum
values for your slider.
To add transparency to a color use
Color c = new Color(red, green, blue, alpha)
Red
, Green
, Blue
and Alpha
all have float values between 0.0 and 1.0.
To change color when the slider is moved, add an event for when the mouse is dragged (you can do this using the visual editor) and use slider.getValue()
to retrieve the value.
To paint the rectangle near the sliders (there should be at least 3 sliders, one for each rbg component) retrieve the slider position and dimensions with slider.getBounds()
(bounds contains x
and y
coordinates plus width
and height
)
Example (draws a rectangle 30x30 20 pixels right the sliders)
private void mouseDragged(java.awt.event.MouseEvent evt) {
color = new Color(sliderRed.getValue(), sliderGreen.getValue(), sliderBlue.getValue());
this.repaint();
}
public void paint(Graphics g) {
g.setColor(color)
g.fillRect(sliderRed.getBounds().x + sliderRed.getBounds().width + 20, sliderRed.getBounds().y, 30, 30);
}
Upvotes: 2