我需要一个 UI,我想在其中描绘网络设备的摆动图形表示。为此,我只是加载多个图像并将它们一一重叠以显示设备的当前状态。我必须支持缩放这个视图。缩放代码如下所示。
public void zoom(double factor){
if (factor < MIN_ZOOM_VALUE)
factor = MIN_ZOOM_VALUE;
else if (factor > MAX_ZOOM_VALUE)
factor = MAX_ZOOM_VALUE;
scaleFactor = factor;
layeredPane.revalidate();
layeredPane.repaint();
}
图像被添加为标签。
private class ImageLabel extends JLabel{
private ImageIcon image;
private Position position;
public ImageLabel(ImageIcon image, Position position){
super(image);
this.image = image;
this.position = position;
}
public void paintComponent(Graphics g) {
int newX = (int)(position.getLeft() * scaleFactor);
int newY = (int)(position.getTop() * scaleFactor);
Graphics2D g2 = (Graphics2D)g;
int newW = (int)(position.getWidth() * scaleFactor);
int newH = (int)(position.getHeight() * scaleFactor);
setBounds(newX, newY, newW, newH);
g2.setRenderingHint(
//RenderingHints.KEY_INTERPOLATION,
//RenderingHints.VALUE_INTERPOLATION_BILINEAR);
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawImage(image.getImage(), 0, 0, newW, newH, null);
}
}
但这里的问题是,当我放大一次并缩小时,一些图像会消失。知道为什么它会这样吗?