我試圖將背景圖像調整爲始終適合其駐留的JPanel。當程序運行它看起來purrfect:JPanel背景圖像調整大小後未填充面板
我遇到的問題是,當我調整窗口的大小,它看起來像這樣:
顯然,形象調整大小,但由於某種原因尚未完全繪製。這是一個更大的應用程序的一部分,但我已經分離出產生問題的代碼,最小的子集:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ScaleTest extends JPanel {
static JFrame window;
static JPanel mainPanel;
BufferedImage originalImage;
BufferedImage scaledImage;
ScaleTest() {
setPreferredSize(new Dimension(320, 200));
try {
originalImage = ImageIO.read(new File("cat.jpg"));
} catch(Exception e){}
addComponentListener(new ResizerListener());
}
public void resize() {
double widthScaleFactor = getWidth()/(double)originalImage.getWidth();
double heightScaleFactor = getHeight()/(double)originalImage.getHeight();
double scaleFactor = (widthScaleFactor > heightScaleFactor)? heightScaleFactor : widthScaleFactor;
AffineTransform at = new AffineTransform();
at.scale(scaleFactor, scaleFactor);
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
scaledImage = scaleOp.filter(originalImage, scaledImage);
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(scaledImage, 0, 0, null);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run(){
window = new JFrame("Scale Test");
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainPanel = new ScaleTest();
window.getContentPane().add(mainPanel);
window.pack();
window.setLocationRelativeTo(null); // positions window in center of screen
window.setVisible(true);
}
});
}
class ResizerListener implements ComponentListener {
@Override
public void componentResized(ComponentEvent e) {
resize();
}
@Override public void componentHidden(ComponentEvent e) {}
@Override public void componentMoved(ComponentEvent e) {}
@Override public void componentShown(ComponentEvent e) {}
}
}
我如何可以使圖像繪製和填充整個JPanel的?
謝謝!完美的工作! –
做了一個很好的改變;) – MadProgrammer
+1,我永遠無法理解所有那些奇特的繪畫函數是如何工作的:) – camickr