/*
* TransparentDraw.java
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class TransparentDraw extends JFrame {
public TransparentDraw() {
super("Click to draw rectangles");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300,210);
setLocationRelativeTo(null);
Background background = new Background();
getContentPane().add(background);
DrawingPanel drawingPanel = new DrawingPanel();
background.add(drawingPanel);
}
public static void main(String args[]) {new TransparentDraw().setVisible(true);}
class DrawingPanel extends JPanel implements MouseListener {
public DrawingPanel() {
setOpaque(false);
setPreferredSize(new Dimension(200,150));
addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (imageBuffer == null) {
imageBuffer = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
g2d = (Graphics2D)imageBuffer.getGraphics();
g2d.setColor(BGCOLOR);
}
g.drawImage(imageBuffer,0,0,BGCOLOR,null);
}
public void mousePressed(MouseEvent evt) {
g2d.fillRect(evt.getX(),evt.getY(),50,50);
repaint();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
private BufferedImage imageBuffer;
private Graphics2D g2d;
private final int OPACITY = 150;
private final Color BGCOLOR = new Color(255, 255, 255, OPACITY);
}
class Background extends JPanel{
public Background(){
System.out.println("Loading image, please wait...");
try{
URL url = new URL(
"http://images.thetimes.co.uk/TGD/picture/0,,223788,00.jpg");
image = ImageIO.read(url);
System.out.println("Image loaded");
}catch(Exception ex){
ex.printStackTrace();
}
}
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.drawImage(image,0,0,null);
}
private BufferedImage image;
}
}