我有一个JPanel(imagePanel),上面有一个图像。我将imagePanel放在另一个JPanel(scrollPanel)里面,用GridBagLayout默认约束来居中它。 scrollPanel是JScrollPane的视口。我需要在事后更改imagePanel的大小并仍然保持居中。 (图像类是我自己制作的一个)
public class ImageView extends View {
private static final long serialVersionUID = -1745026846891845769L;
private JScrollPane scrollPane;
private JPanel scrollPanel;
public JPanel imagePanel;
public int zoom = 1;
public Image image;
public ImageView(Image image) {
setLayout(new BorderLayout());
setDoubleBuffered(true);
this.image = image;
imagePanel = new JPanel() {
private static final long serialVersionUID = 2127374649591395224L;
@Override
public void paint(Graphics g) {
super.paint(g);
ImageView.this.image.paintImage(g, 0, 0, zoom);
}
};
imagePanel.setDoubleBuffered(true);
scrollPanel = new JPanel(new GridBagLayout());
scrollPanel.add(imagePanel);
scrollPane = new JScrollPane(scrollPanel);
add(scrollPane, BorderLayout.CENTER);
}
public void zoom(int zoom) {
if(zoom < 1)
this.zoom = 1;
else
this.zoom = zoom;
int imageWidth = image.WIDTH * this.zoom;
int imageHeight = image.HEIGHT * this.zoom;
imagePanel.setPreferredSize(new Dimension(imageWidth, imageHeight));
//What do I do here???
}
编辑:这是我为其他任何有相同问题的人更新的代码
public class ImageView extends View {
private static final long serialVersionUID = -1745026846891845769L;
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 2127374649591395224L;
public int zoom = 1;
public void setZoom(int zoom) {
if(zoom < 1)
this.zoom = 1;
else
this.zoom = zoom;
}
@Override
public Dimension getPreferredSize() {
int imageWidth = ImageView.this.image.WIDTH * this.zoom;
int imageHeight = ImageView.this.image.HEIGHT * this.zoom;
return new Dimension(imageWidth, imageHeight);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageView.this.image.paintImage(g, 0, 0, zoom);
}
}
private JScrollPane scrollPane;
private JPanel scrollPanel;
public ImagePanel imagePanel;
public Image image;
public ImageView(Image image) {
setLayout(new BorderLayout());
setDoubleBuffered(true);
this.image = image;
imagePanel = new ImagePanel();
imagePanel.setDoubleBuffered(true);
scrollPanel = new JPanel(new GridBagLayout());
scrollPanel.add(imagePanel);
scrollPane = new JScrollPane(scrollPanel);
add(scrollPane, BorderLayout.CENTER);
}
public void zoom(int zoom) {
imagePanel.setZoom(zoom);
scrollPanel.revalidate();
scrollPanel.repaint();
}
答案 0 :(得分:3)
不要调用setPreferredSize()。
您应该覆盖类的getPreferredSize()
方法来进行大小计算。所以基本上应该在该方法中定义缩放逻辑。
然后在zoom(..)方法中调用:
revalidate();
repaint();
zoom()
方法应该是绘制图像的面板的一部分,因为缩放系数是此面板的属性。这将导致调用布局管理器,并且将在组件的布局中使用新的首选大小。
此外,您应该覆盖paintComponent(...)
方法,而不是paint(...)方法来绘制图像。
答案 1 :(得分:0)
根据此链接:http://www.coderanch.com/t/333435/GUI/java/Whats-exact-difference-paint-repaint 调用setPreferedSize
后,您可能需要调用validate