我在Java中绘制一个Image,如果调整大小,我想将Image更新为窗口大小。但由于我是初学者,我根本不知道应该做些什么。
public class ImageCanvas extends JFrame {
private static final long serialVersionUID = 1L;
JPanel panel;
JLabel label;
ImageIcon icon;
BufferedImage image;
public ImageCanvas() throws IOException{
draw();
icon = new ImageIcon(image);
label = new JLabel(icon);
panel = new JPanel();
panel.add(label);
getContentPane().add(panel);
setSize(image.getWidth()+10, image.getHeight());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
File f = new File("c:\\img.png");
ImageIO.write(image, "png", f);
}
private void draw() {
int width = 640, height = 480;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
WritableRaster raster = image.getRaster();
ColorModel model = image.getColorModel();
Color c1 = Color.BLACK;
int argb1 = c1.getRGB();
Object data1 = model.getDataElements(argb1, null);
Color c2 = Color.RED;
int argb2 = c2.getRGB();
Object data2 = model.getDataElements(argb2, null);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
raster.setDataElements(i, j, data1);
if(i==j){
raster.setDataElements(i, j, data2);
}
}
}
}
public static void main(String args[]) throws IOException {
new ImageCanvas();
}
}
答案 0 :(得分:0)
JLabel始终将图标绘制为实际尺寸。每次调整标签大小时,都需要重新创建图像。
更简单的方法是进行动态绘制,根据需要调整图像大小。 Background Panel可以为您做到这一点。