Search code examples
javaswingcolorsjslider

Adding color to JLabel next to my JSliders


Wanting to change the text color of Red,Green,Blue to their appropriate colors in my JLabel with keeping my background and JSliders still the default color of the program. I am not concerned with the Height and Width colors, but just the Text next to the JSliders that say Red,Blue, and Green. Any help is appreciated! Thank you!

import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import javax.swing.event.*;
public class ControlApp extends JFrame
{
    private JPanel mainPanel;
    private PrintWriter out;
    private JSlider height,width,red,green,blue;
    private String aspect;
    private String value;

public static void main(String []args)
{
    new ControlApp();
}

public ControlApp()
{
    super("ControlApp");
    mainPanel = new JPanel();
    add(mainPanel,BorderLayout.CENTER);

    //SliderListener sl = new SliderListener();

    height = new JSlider(JSlider.VERTICAL, 0,500,0);
    //height.addChangeListener(sl);
    width = new JSlider(JSlider.VERTICAL, 0,500,0);
    //width.addChangeListener(sl);
    red = new JSlider(JSlider.VERTICAL, 0,255,0);
    //red.addChangeListener(sl);       
    green = new JSlider(JSlider.VERTICAL, 0,255,0);
    //green.addChangeListener(sl);
    blue = new JSlider(JSlider.VERTICAL, 0,255,0);
    //blue.addChangeListener(sl);

    mainPanel.add(new JLabel("Height"));
    mainPanel.add(height,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Width"));
    mainPanel.add(width,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Red"));
    mainPanel.add(red,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Green"));
    mainPanel.add(green,BorderLayout.CENTER);
    mainPanel.add(new JLabel("Blue"));
    mainPanel.add(blue,BorderLayout.CENTER);

    setLocationRelativeTo(null);
    this.setSize(500,250);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}
}

Solution

  • ttrigger10 -

    You want to set the foreground color on those JLabels to get them to be a specific color with the setForgroundColor method. See the modified code below to change the colors:

        JLabel redLabel, blueLabel, greenLabel;
        redLabel = new JLabel("Red");
        redLabel.setForeground(Color.RED);
        greenLabel = new JLabel("Green");
        greenLabel.setForeground(Color.GREEN);
        blueLabel = new JLabel("Blue");
        blueLabel.setForeground(Color.BLUE);
    
        mainPanel.add(new JLabel("Height"));
        mainPanel.add(height, BorderLayout.CENTER);
        mainPanel.add(new JLabel("Width"));
        mainPanel.add(width, BorderLayout.CENTER);
        mainPanel.add(redLabel);
        mainPanel.add(red, BorderLayout.CENTER);
        mainPanel.add(greenLabel);
        mainPanel.add(green, BorderLayout.CENTER);
        mainPanel.add(blueLabel);
        mainPanel.add(blue, BorderLayout.CENTER);