1

textArea.setBackground(Color.RED); allows you to add a specific color into it, but what if I want to add a Gradient color to it

well the code is as follows

public class IncomingTextArea extends JTextArea {

IncomingTextArea(int width,int height){
    super(width,height);
}
@Override
public void paintComponent(Graphics g) {

    Graphics2D g2D = (Graphics2D) g;

    int red = (int) Math.random() * 255;
    int green = (int) Math.random() * 255;
    int blue = (int) Math.random() * 255;
    Color startColor = new Color(red, green, blue);

    red = (int) Math.random() * 255;
    green = (int) Math.random() * 255;
    blue = (int) Math.random() * 255;
    Color endColor = new Color(red, green, blue);

    GradientPaint gradientPaint = new GradientPaint(70, 70, startColor, 150, 150, endColor);
    g2D.**??**
    super.paintComponent(g2D);

}

}

but I just can't find the right method to assign gradient value to it. well .paint(gradientPaint) works for shapes and stuff, but what about whole textArea ?

mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

2

I was wrong -- don't extend JTextArea, but rather extend the JViewport of the JScrollPane that holds your JTextArea, draw within its paintComponent method, and make sure that your JTextArea is non-opaque.

So I'd extend the viewport like so:

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JViewport;

public @SuppressWarnings("serial") class GradientViewport extends JViewport {
    private Color c1;
    private Color c2;

    public GradientViewport(Color c1, Color c2) {
        this.c1 = c1;
        this.c2 = c2;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        GradientPaint gPaint = new GradientPaint(0, 0, c1, getWidth(), getHeight(), c2, false);
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(gPaint);
        g2.fillRect(0, 0, getWidth(), getHeight());
    }

}

again, drawing the gradient within the viewport's paintComponent method.

I'd then use it like so:

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class GradientTextAreaTest extends JPanel {
    public static final Color C1 = new Color(255, 200, 200);
    public static final Color C2 = new Color(200, 200, 255);
    private JTextArea textArea = new JTextArea(30, 40);

    // create the view port with colors passed into it
    private GradientViewport viewport = new GradientViewport(C1, C2);
    private JScrollPane scrollPane = new JScrollPane();

    public GradientTextAreaTest() {
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        // make the JTextArea transparent
        textArea.setOpaque(false);

        // set the viewport's view with your JTextArea
        viewport.setView(textArea);

        // set the JScrollPane's viewport with our viewport object
        scrollPane.setViewport(viewport);

        // add the JScrollPane to our GUI
        add(scrollPane);
    }

    private static void createAndShowGui() {
        GradientTextAreaTest mainPanel = new GradientTextAreaTest();

        JFrame frame = new JFrame("GradientTextAreaTest");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

}

Or to display this:

enter image description here

Use the above class like so:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class GradientTextAreaTest extends JPanel {
    public static final String TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
            + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut "
            + "aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu "
            + "fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit "
            + "anim id est laborum.";
    public static final int FILLER = 130;
    public static final Color C1 = new Color(255, FILLER, FILLER);
    public static final Color C2 = new Color(FILLER, FILLER, 255);
    private JTextArea textArea = new JTextArea(14, 30);

    // create the view port with colors passed into it
    private GradientViewport viewport = new GradientViewport(C1, C2);
    private JScrollPane scrollPane = new JScrollPane();

    public GradientTextAreaTest() {
        setLayout(new BorderLayout());
        textArea.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 32));
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        for (int i = 0; i < 10; i++) {
            textArea.append(TEXT + "\n");
        }

        // make the JTextArea transparent
        textArea.setOpaque(false);

        // set the viewport's view with your JTextArea
        viewport.setView(textArea);

        // set the JScrollPane's viewport with our viewport object
        scrollPane.setViewport(viewport);

        // add the JScrollPane to our GUI
        add(scrollPane);
    }

    private static void createAndShowGui() {
        GradientTextAreaTest mainPanel = new GradientTextAreaTest();

        JFrame frame = new JFrame("GradientTextAreaTest");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • just edited the post, can you fill the `QuestionMark`? –  Feb 19 '17 at 15:18
  • @D4G4: What? I've posted the answer above. There is nothing that you can do in the question mark that will solve your problem as **again** the solution is to override the JScrollPane's viewport, not the JTextArea. – Hovercraft Full Of Eels Feb 19 '17 at 15:26
  • 1
    @HovercraftFullOfEels Well, you could do either depending on what you want to achieve, as an [example](http://stackoverflow.com/questions/13677850/add-background-image-in-jtable/13678077#13678077) using a `JTable` ;) – MadProgrammer Feb 19 '17 at 20:32
0

The method told by @Hovercraft Full Of Eels is quite good

Well, I've found another fix. Paint the rectangle or any other object with your gradient as usual i.e. g2D.setPaint(gradientPaint); g2D.fillRect(0, 0, getWidth(), getHeight());

and then textArea.setOpaque(false);

Kind of hit and trial I know :p

But thanks @Hovercraft Full Of Eels

  • 1
    Before for or after you call `super.paintComponent`? The text of the text area is painted by `paintComponent` so you could end up wiping out the text if your not careful - as [demonstrated](http://stackoverflow.com/questions/26386422/how-to-set-background-image-to-a-jtextarea-in-a-jpanel/26391459#26391459) – MadProgrammer Feb 19 '17 at 20:33
  • Will set RGB values greater than 150.. Well this was simply a Client Server text chat application.. Was just adding stuff from my own.. I'm just an intermediate.. So :) –  Feb 19 '17 at 20:50