0

我正在用 Java 绘制图像,如果调整大小,我想将图像更新为窗口的大小。但由于我是初学者,我根本不知道我应该做什么。

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(); 
    }
}
4

1 回答 1

0

JLabel 总是将图标绘制为其实际大小。每次调整标签大小时,您都需要重新创建图像。

一种更简单的方法是进行动态绘画,这将根据需要调整图像大小。背景面板可以为您做到这一点。

于 2013-04-23T03:53:51.530 回答