Saturday, May 15, 2021

[Java Code Sample] Adding background image to JTextArea

Unlike JLabel, JTextArea doesn't have a function to set image on its background.

So let's create a "new" JTextArea which can display images.



Please check this video tutorial for the detailed explanation:





Main class


import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;


public class Main {

	public static void main(String[] args) {
		
		new Main();

	}
	public Main() {
		
		JFrame window = new JFrame();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setSize(1280,840);
		

		JTextAreaPlus textAreaPlus = new JTextAreaPlus("This is a sample text");
		textAreaPlus.setFont(new Font("Times New Roman", Font.PLAIN, 36));
		ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("forest01.jpg"));
		textAreaPlus.setImage(icon,0,0,1280,840);
		textAreaPlus.setForeground(Color.white);
		
		window.add(textAreaPlus);
		
		window.setVisible(true);
	}
}

JTextAreaPlus class


import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;

public class JTextAreaPlus extends JTextArea{
	
	Image image;
	int x, y, width, height;

	public JTextAreaPlus() {
		super();
	}
	public JTextAreaPlus(String text) {
		super(text);
	}
	
	public void setImage(ImageIcon icon, int x, int y, int width, int height) {
		
		this.image = icon.getImage();
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		setOpaque(false);
		repaint();
	}
	public void paint(Graphics g) {
		
		g.drawImage(image,x,y,width,height,null);	
		super.paint(g);
	}
}


You can set an image, the image's location and its size with the "setImage" method.

Result:


No comments:

Post a Comment