我正在使用需要使用透明图像的JFrame制作应用程序,例如:
但是,每当我尝试将图像添加到我的JFrame时,我都会得到:
有人可以帮我弄清楚如何使其正常工作吗?帮助将不胜感激!
以下是相关代码:
public class Canvas
{
private JFrame frame;
private CanvasPane canvas;
private Graphics2D graphic;
private Color backgroundColour;
private Image canvasImage;
public Canvas(String title, int width, int height, Color bgColour)
{
frame = new JFrame();
canvas = new CanvasPane();
frame.setContentPane(canvas);
frame.setTitle(title);
canvas.setPreferredSize(new Dimension(width, height));
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
backgroundColour = bgColour;
frame.pack();
setVisible(true);
}
public void setVisible(boolean visible)
{
if(graphic == null) {
// first time: instantiate the offscreen image and fill it with
// the background colour
Dimension size = canvas.getSize();
canvasImage = canvas.createImage(size.width, size.height);
graphic = (Graphics2D)canvasImage.getGraphics();
graphic.setColor(backgroundColour);
graphic.fillRect(0, 0, size.width, size.height);
graphic.setColor(Color.black);
}
frame.setVisible(true);
}
public boolean drawImage(Image image, int x, int y)
{
boolean result = graphic.drawImage(image, x, y, null);
canvas.repaint();
return result;
}
private class CanvasPane extends JPanel
{
private CanvasPane(){
setOpaque(false);
}
public void paint(Graphics g)
{
g.drawImage(canvasImage, 0, 0, null);
}
}
}
如果您需要更多代码,请告诉我!