class yourclass extends Jwindow{
.....
jLabel.setIcon(new ImageIcon(new java.net.URL(youfilepath)));
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(jLabel1,BorderLayout.CENTER);
pack()
.....
jLabel.setIcon(new ImageIcon(new java.net.URL(youfilepath)));
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(jLabel1,BorderLayout.CENTER);
pack()
1.pack方法是让窗口自动调整大小适应自己的内部控件,而不是让内部图片自动调整大小适应窗口
2.我需要的代码是让控件显示图片(Component类)而不是窗口,因为窗口有菜单栏等东西,是我不希望看到的
你的组件例如JPanel对象,它的宽度是cw ,高度是ch 。
可以使用Image 类的getScaledInstance方法:
public Image getScaledInstance(int width,
int height,
int hints)Creates a scaled version of this image. A new Image object is returned which will render the image at the specified width and height by default. The new Image object may be loaded asynchronously even if the original source image has already been loaded completely. If either the width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions. Parameters:
width - the width to which to scale the image. (需要缩放的宽度)
height - the height to which to scale the image. (需要缩放的高度)
hints - flags to indicate the type of algorithm to use for image resampling. (重新采样使用的插值算法)
Returns:
a scaled version of the image.
应该可以满足你的要求。
int x,
int y,
int width,
int height,
Color bgcolor,
ImageObserver observer)方法吧
在改变大小的时候重画控件。
如果是固定大小的话,你要考虑控件的形状与Image德形状不同,所以
要考虑宽和高的比例,不然一部分图像可能显示不出来。
我继承JComponent作了个ImageViwer,可以改变大小,图片自动缩放。
你根据JComponent算出合适的大小时,重载paintComponent(Graphics g)
方法就可以了,可以这么写(thumbnail是算出合适的大小生成的Image)if (thumbnail == null) {
loadImage();
} if (thumbnail != null) {
int x = getWidth()/2 - thumbnail.getIconWidth()/2;
int y = getHeight()/2 - thumbnail.getIconHeight()/2; if (y < 0) {
y = 0;
} if (x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
}