我已经在这个问题上卡了一天了。我想动态更新一个叫 BufferedImage
绘制在一个透明无边框的窗口之上。但是,当窗口背景的alpha值被设置为除full之外的任何其他值时,repaint()就会停止工作(1.0f
);
我试过了 image_canvas.setOpaque(false)
但这并没有解决这个问题。
请告诉我,如果有人能找到一个解决办法,让组件的 repaint()
在透明背景上工作。
下面的代码可以重现这个问题。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Window;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
public class Dynamic_Buffered_Image2 {
static Window win;
static JComponent image_canvas;
static BufferedImage my_image;
public static void main(String[] args) throws InterruptedException {
// Create a test BufferedImage:
my_image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < 100; i++)
my_image.setRGB(i, i, Color.BLUE.getRGB());
// Create display window:
create_win();
// Modify the BufferedImage dynamically:
for (int i = 0; i < my_image.getWidth(); i++) {
for (int j = 0; j < my_image.getHeight(); j++) {
my_image.setRGB(i, j, Color.red.getRGB());
Thread.sleep(10);
win.repaint();
}
}
}
private static void create_win() {
win = new Window(null);
win.setSize(150, 150);
image_canvas = new JComponent() {
private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g) {
g.drawImage(my_image, 0, 0, null);
}
};
win.add(image_canvas);
win.setBackground(new Color(0, 0, 0, 1.0f)); // Any opacity other than 1.0f breaks repaint()??? (no red lines)
win.setVisible(true);
}
}
我做了两个改动。
//win.repaint();
image_canvas.repaint();
我做了两处改动:
image_canvas.setOpaque(true); // added
win.add(image_canvas);