Search code examples
javaswingjtextareajcolorchooser

How to make it so that the color you pick in a JColorChooser changes the color of the font in a JTextArea?


I'm making a basic Text Editor and i want it so where you can select a color in the JColorChooser and the color that you chose will be the new color of the Text in the JTextArea. This is the code for the JColorChooser

JPanel panel = new JPanel();
        JColorChooser color = new JColorChooser();

        panel.add(color);

        int x = JOptionPane.showConfirmDialog(null, panel, "Pick a Color", JOptionPane.OK_CANCEL_OPTION, -1);
        if(x == JOptionPane.OK_OPTION){
            <Code Here>
        }
        if(x == JOptionPane.CANCEL_OPTION){

        }else{

        }

and the JText Area's code is

static JTextArea textArea;

private Font textFont;

NVM IT HAS BEEN ANSWERED

Color newColor = color.getColor();
                textArea.setForeground(newColor);

Solution

  • Read the section from the Swing tutorial on How to Use Color Choosers.

    The ColorChooserDemo will show you how to do this. It change the foreground of a JLabel, but the concept would be the same for a JTextArea.

    Also, the tutorial example will show you how to better structure your code. You should NOT be using static variables in your code.