简体   繁体   中英

How to change text color in JTextPane

I want to change the text I have written (and the font color) to another color depending on what the user wants.

I made a JFrame, and added JTextPane. To the right of the TextPane I have a list with different colors ("White", "Black", "Green", etc). The Jframe also has a JMenuBar and, if the user highlights one of the elements in the list (Say Black) I want to change the background color of the textpane ( I know it's silly, but it's an assignment from our teacher)

The problem is though, the text is black, so when I change the background color, the text "dissapears". I want to change the text to white when the background color is set to black.

It's kind of weird, I can write

textPane.setForeground(Color.White)

in the constructor and it works fine. The text is white, (or green, or whatever color I chose) but when I add it in my ActionListener it doesnt work? How can I fix it?

Here is my code:

if (e.getSource().equals(changeColor)) {
    if (list.getSelectedValue().equals("White")) {
        textPane.setForeground(Color.BLACK);
        textPane.setBackground(Color.WHITE);

    }
    if(list.getSelectedValue().equals("Black")){
        textPane.setForeGround(Color.WHITE);
        textPane.setBackground(Color.BLACK);
    }
}

Try "repainting" the textPane

textPane.repaint();
textPane.invalidate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM