I have a JPanel (imagePanel) that shows an image on it. I have imagePanel inside another JPanel (scrollPanel) with GridBagLayout default constraints to center it. scrollPanel is the viewport for a JScrollPane. I need to change the size of the imagePanel after the fact and still keep it centered. (The image class is one I made myself)
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???
}
EDIT: Here is my updated code for anyone else with the same question
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();
}