Question

I tried to change the foreground font color of this transcluent JTextArea to black, but it remains blue-gray. What am I doing wrong?

    // [8]*HELP TEXTAREA
    JTextArea help_text = new JTextArea () {
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            Insets insets = getInsets();
            int x = insets.left;
            int y = insets.top;
            int width = getWidth() - (insets.left + insets.right);
            int height = getHeight() - (insets.top + insets.bottom);
            g2d.setColor(new Color(255, 0, 0, 70));
            g2d.fillRect(x, y, width, height);
            super.paintComponent(g);
        }
    };
    help_text.setFont(new Font(Font.MONOSPACED,Font.BOLD, 70));
    help_text.setForeground(Color.black);
    help_text.setOpaque(false);
    help_text.setLineWrap(true);
    help_text.setWrapStyleWord(true);
    help_text.setEditable(false);
    help_text.setEnabled(false);
    help_text.setHighlighter(null); 
    help_text.setText("Some help text . ..");
    // [8]*HELP PANE
    JScrollPane help_pane = new JScrollPane(help_text);
    help_pane.setOpaque(false);
    help_pane.getViewport().setOpaque(false);  
Was it helpful?

Solution

Change:

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Insets insets = getInsets();
    int x = insets.left;
    int y = insets.top;
    int width = getWidth() - (insets.left + insets.right);
    int height = getHeight() - (insets.top + insets.bottom);
    g2d.setColor(new Color(255, 0, 0, 70));
    g2d.fillRect(x, y, width, height);
    super.paintComponent(g);
}

into:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    Insets insets = getInsets();
    int x = insets.left;
    int y = insets.top;
    int width = getWidth() - (insets.left + insets.right);
    int height = getHeight() - (insets.top + insets.bottom);
    g2d.setColor(new Color(255, 0, 0, 70));
    g2d.fillRect(x, y, width, height);

    g2d.dispose();
}

I believe this should solve your problem, since from what it seems by your code, there are two potential problems with it:

  • You're cancelling all the painting you're doing by calling super.paintComponent(g) as the last line of code
  • You're changing the state of the Graphics object you receive, which is used by the entire component hierarchy, and which state should be preserved
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top