Home Tutorial Java Swing Set Transparent Background Image

 
 

Share on Google+Share on Google+
Set Transparent Background Image
Posted on: May 13, 2010 at 12:00 AM
Advertisement
Here we are going to give the transparent effect to the image.

Set Transparent Background Image

Swing components not only allow you to change the background color of a component, but also you can give the beautiful look to your frame or other components by setting the transparent background image on the frame. Here we are going to give the transparent effect to the image. For this, we have used paint(Graphics g) method of JComponent class to draw an image on the panel. Then we have set  setOpaque() value false for panel and all the components that are added to panel .This makes the image transparent and gives the beautiful look to the frame.

Here is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TransparentBackgroundImage {
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				Window win = e.getWindow();
				win.setVisible(false);
				win.dispose();
				System.exit(0);
			}
		});
		JPanel panel = new JPanel(new GridLayout(2, 2)) {
			ImageIcon image = new ImageIcon("C:/rose.jpg");

			public void paint(Graphics g) {
				Dimension d = getSize();
				for (int x = 0; x < d.width; x += image.getIconWidth())
					for (int y = 0; y < d.height; y += image.getIconHeight())
						g.drawImage(image.getImage(), x, y, null, null);
				super.paint(g);
			}
		};
		JLabel l1 = new JLabel("Name");
		JLabel l2 = new JLabel("Address");
		JTextField text = new JTextField(20);
		JTextField text1 = new JTextField(20);
		panel.setOpaque(false);
		text.setOpaque(false);
		text1.setOpaque(false);
		panel.add(l1);
		panel.add(text);
		panel.add(l2);
		panel.add(text1);
		frame.add(panel);

		frame.setSize(300, 100);
		frame.show();
	}
}

Output:

Advertisement

Related Tags for Set Transparent Background Image:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 13, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com