Set Gradient for Caret in JTextArea

JTextArea containing a gradient painted caret.
You can even customize the caret in JTextArea and set gradient for it by extending the DefaultCaret class and overriding the paint() method. This program is very simple and understandable if you are acquainted with the basics of the caret. It is important to know that a caret is a line (usually blinking) that represents focus on a text component. You have seen it many times! (See it is in the side of the image after Gowtham Gutha, the gradient line!). Now let us see how to do it.

import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
import java.awt.geom.*;
class CustomTextAreaCaret extends JFrame
{
JTextArea jt;
JScrollPane js;

    public CustomTextAreaCaret()
    {
        createAndShowGUI();
    }
  
    private void createAndShowGUI()
    {
        // Set title and default close operation
        setTitle("TextArea Caret");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // Create JTextArea
        jt=new JTextArea();
       
        // Set some font
        jt.setFont(new Font("Roboto",Font.BOLD,27));
       
        // Create JScrollPane for jt
        js=new JScrollPane(jt);
       
        // Set custom caret
        jt.setCaret(new DefaultCaret(){
            public void paint(Graphics g)
            {
           
            // Get Graphics2D object to work
            // with gradient paint
            Graphics2D g2=(Graphics2D)g;
                try
                {
                    // Convert model to view, so that we get
                    // a rectangle whose x and y co ordinate
                    // is the x,y of the caret and width and height
                    // is the width and height of the caret
                    Rectangle r=jt.modelToView(jt.getCaretPosition());
                   
                    // Set some gradient paint for the caret
                    // The gradient starting should be the x,y of the caret (which changes with
                    // caret position) and the starting of the second color should be
                    // x,r.y+height. r.y+r.height is used so that it will act like a linear
                    // gradient paint. The gradient comes with red at top, gray at bottom
                    g2.setPaint(new GradientPaint(r.x,r.y,Color.RED,r.x,r.y+r.height,Color.GRAY));
                                       
                    // Fill the shape with the gradient
                    // The shape starting should be r.x,r.y (pos of caret)
                    // and width should be 2 and height is height of the caret (which
                    // depends upon the font height
                    g2.fill(new java.awt.geom.Rectangle2D.Double(r.x,r.y,2,r.height));
                   
                }catch(Exception e){}
            }
           
        });
       
        // Add JScrollPane
        add(js);

        // Set size,center the JFrame, show it.
        setSize(400,400);
        setLocationRelativeTo(null);
        setVisible(true);
    }
       
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new CustomTextAreaCaret();
            }
        });
    }
}

In this way, we can set the gradient for caret in JTextArea or draw an image or do whatever you want with the help of the Graphics object. If this post is worth sharing, feel free to share it and also drop a comment for any queries and suggestions. You might also like other posts on how to set background image in JTextArea and load text in JTextArea with random speed

No comments: