在做一个类似略缩图功能的东西,自定义了一个继承自JComponent的Thumbnail类,当把这个Thumbnail类直接添加到JFrame时,图片显示没有问题,但是当我先添加到JPanel内,再将JPanel添加到JFrame时,图片只有一个点。如果Thumbnail类改为继承自JPanel,则图片大小只有10*10。求解,代码如下。
- Java code
import javax.swing.*;import javax.imageio.*;;import java.awt.*;import java.awt.geom.*;import java.io.*;public class TestTh extends JFrame{ public static void main(String[] args){ TestTh t = new TestTh(); t.setSize(600, 400); t.setVisible(true); t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); t.add(new Thumbnail("G:\\Image\\image.jpg")); }}class Thumbnail extends JComponent{ private Image img; double ratio; String path; private AffineTransform af = AffineTransform.getScaleInstance(1,1); public Thumbnail(){ setSize(180, 200); } public void setPath(String path){ this.path = path; } public Thumbnail(String path){ this.path = path; setSize(180, 200); setImage(); } private void setImage(){ try{ img = ImageIO.read(new File(path)); ratio = culculateRatio(img.getWidth(null),img.getHeight(null)); //paintImmediately(getBounds()); }catch(IOException ex){ System.out.println("Can not find this file!"); } //paintImmediately(getBounds()); concateZoom(ratio); } private void concateZoom(double scale){ if (img==null)return; af.preConcatenate(AffineTransform.getScaleInstance(scale,scale)); paintImmediately(getBounds()); System.out.println(getWidth() + "&" + getHeight());//此处输出180 & 200 } @Override protected void paintComponent(Graphics g) { System.out.println(getWidth() + "*" + getHeight());//此处输出1 * 1,最终画出的图只有一个点 super.paintComponent(g); if (img==null) { g.setColor(Color.BLACK); g.fillRect(0,0,getWidth(),getHeight()); } else { Graphics2D g2d = (Graphics2D)g; g2d.setTransform(af); g2d.drawImage(img, (int)(((getWidth()-img.getWidth(null)*ratio)/2)/ratio), (int)(((getHeight()-img.getHeight(null)*ratio)/2)/ratio), this); } }//paintComponent final double culculateRatio(int width, int height){//计算缩放比率 //System.out.println(getWidth() + "*" + getHeight()); if(getWidth()>=width && getHeight()>=height) return 1; if((double)getWidth()/width > (double)getHeight()/height) return (double)getHeight() / height; else return (double)getWidth() / width; }//culculateRatio}//Thumbnail
------解决方案--------------------
把 setSize =》 setPreferredSize
------解决方案--------------------