我想调整图片大小,但显示它总是出错。
我该怎么办?
public class Panel extends JPanel {
private ImageIcon imgIcon;
public Panel(){
super();
File imageFile=new File("mar.jpg");
try {
BufferedImage bi = ImageIO.read(imageFile);
ImageIcon imgIcon = new ImageIcon(bi);
imgIcon = new ImageIcon(bi.getScaledInstance(400,400, Image.SCALE_DEFAULT));
} catch (IOException e) {
System.err.println("error");
e.printStackTrace();
}
Dimension dimension=new Dimension(1400,1000);
setPreferredSize(dimension);
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(imgIcon.getImage(),0,0,this);
}
}
答案 0 :(得分:0)
这就是我过去的做法:
public class ImagePanel extends JPanel{
private BufferedImage image;
public PanelImage(){}
public void setImage(BufferedImage image){
this.image = image;
}
private Image scaleImage(){
if(image==null)return null;
int width = getWidth();
int height = (int)((getWidth()/(double)image.getWidth())*image.getHeight());
return image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
}
@Override protected void paintComponent(Graphics g){
super.paintComponent(g);
Image scaledImage = scaleImage();
if(scaledImage != null){
int x = 0;
int y = (int)((getHeight()/2d)-(scaledImage.getHeight(null)/2d));
g.drawImage(scaledImage, x, y, null);
}
}
}
此外,请不要将您的课程命名为Panel
,因为已经存在awt.Panel
并且会导致歧义问题。