📄 imagepane.java
字号:
package za.co.halo.SecureCommunications.util;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
/**
* ImagePanel can be used to display an image in a
* container.
*/
public class ImagePane extends JPanel implements Printable
{
private Icon image;
private int width, height;
/**
* Constructs a new ImagePanel with the specified image
* on the specified location. Theimage is scaled to fit
* in this panel.
*
* @param image
* The image to put on this panel.
* @param width
* The width of the panel.
* @param height
* The height of the panel.
*/
public ImagePane(ImageIcon image, int width, int height)
{
setPreferredSize(new Dimension(width, height));
this.width = width;
this.height = height;
setImage(image);
}
/**
* Sets the image of this panel and repaints it.
*
* @param image
* The new image to displayed on this panel.
*/
public void changeImage(ImageIcon image)
{
setImage(image);
repaint();
}
/**
* @see javax.swing.JComponent#paint(java.awt.Graphics)
*/
@Override
public void paint(Graphics g)
{
super.paint(g);
paint(g, 0, 0);
}
/**
* @see za.co.iocom.gui.custom.Offsetable#paint(java.awt.Graphics,
* int, int)
*/
public void paint(Graphics g, int xx, int yy)
{
Graphics2D g2 = (Graphics2D) g;
//super.paint(g);
if (image != null)
image.paintIcon(this, g2, (width - image.getIconWidth()) / 2 + xx, (height - image
.getIconHeight())
/ 2 + yy);
}
/**
* @see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
public int print(Graphics g, PageFormat p, int i)
{
paint(g, (int) p.getImageableX(), (int) p.getImageableY());
return Printable.PAGE_EXISTS;
}
/**
* Sets the image of this panel, without repainting it.
*
* @param image
* The new image to displayed on this panel.
*/
public void setImage(ImageIcon image)
{
if (image != null)
this.image = scaleCopy(image, width, height);
else
this.image = null;
}
/**
* Scale a ImageIcon to the specified x and y scale The
* optimal scaling algorithm is used. Aspect ration is
* conserved. In effect this scales the image so that it
* can fit into the rectangle of width scaleX and height
* scaleY
*
* @param image
* The image to scale
* @param scaleX
* The maximum width of the new image.
* @param scaleY
* The maximum height of the new imag.
* @return A new scaled version of the ImageIcon.
*/
public static ImageIcon scaleCopy(ImageIcon image, int scaleX, int scaleY)
{
Image im = image.getImage();
Image scaledIm;
if ((double) image.getIconWidth() / image.getIconHeight() < (double) scaleX / scaleY)
scaledIm = im.getScaledInstance(-1, (scaleY), Image.SCALE_SMOOTH);
else
scaledIm = im.getScaledInstance((scaleX), -1, Image.SCALE_SMOOTH);
return new ImageIcon(scaledIm);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -