这是我的相关代码
protected JPanel createRightPane() {
final ImageIcon BGiconSM = ScaledImageIcon("parchmentTall.jpg", "BG Plate", initalWidth/2, initalHeight);
final ImageIcon iconSM = ScaledImageIcon("titlebar.png", "Title Bar BG", (initalWidth/3), 40);
//TODO Parchment image resize
final JPanel content = new JPanel(new GridBagLayout());
content.setOpaque(false);
final JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
Image BGicon = BGiconSM.getImage();
g.drawImage(BGicon, 0, 0, null);
super.paintComponent(g);
}
};
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e){
Rectangle r = frame.getBounds();
int h = r.height;
int w = r.width;
if (h >= initalHeight){h = initalHeight-30;}
//System.out.println(h);
//System.out.println(w);
/* protected paintComponent(Graphics g)
{
// Dispaly image at full size
Image BGicon = BGiconSM.getImage();
g.drawImage(BGicon, 0, 0, null);
super.paintComponent(g);
}
*/
}
});
答案 0 :(得分:3)
问题是,为什么要(调整大小)?您只告诉Graphics
上下文它应该在组件的左上角绘制图像(0x0)。
您应该查看Graphics#drawImage(Image, int, int, int, int, ImageObserver)
和Graphics2D#drawImage(Image, AffineTransform, ImageObserver)
您还应该看看:
关于缩放图像的不同方法的讨论
你也打破了油漆链,这导致了“白墙”。在执行任何自定义绘画之前,您应该调用super.paintComponent
。
为了自定义绘制而覆盖像JPanel
或JComponent
这样的容器时,您还应该考虑重写getPreferredSize
方法,这将为布局管理器提供调整大小的方法将组件调整为适当的默认大小,而不是使用0x0
,这通常是默认大小。
答案 1 :(得分:1)
你可以为你的面板添加一个监听器......
How can I force an ImageIcon to be a certain size?
按钮上有一个解决方案,但您可以非常轻松地取消这些组件......
(复制/粘贴)
那么如何测量按钮尺寸?
final JPanel panel = new JPanel(); //create it on your custom way...
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e){
int w = b.getWidth();
int h = b.getHeight();
setIconSize(w,h); //TODO by yourself (sorry, if more help required please say so)
}
});
您只需使用以下代码缩放图片:
/**
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
* Resizes an image using a Graphics2D object backed by a BufferedImage.
* @param srcImg - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}