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();
}
}
1)'private void draw(){'method should be'@Override public void paint(Graphics g){'instead。但是這應該是'JPanel'中的'paintComponent(Graphics)',它返回基於圖像原始大小的首選大小和最大大小,但繪製了[縮放圖像](http://docs.oracle.com) /javase/7/docs/api/java/awt/geom/AffineTransform.html#getScaleInstance%28double,%20double%29)。 2)'setSize(image.getWidth()+ 10,image.getHeight());'改爲'pack();'。 3)'setLocationRelativeTo(null);'改爲'setLocationByPlatform(true); // nice..';) – 2013-04-23 04:11:37