I am trying to build an application that displays an image in a JScrollPane. I have written a class that extends JPanel of which I override the paintComponent() function to paint the image on the JPanel. This is then added to the JScrollPane. The problem is this, the JPanel is displayed as the same size as the JScrollPane and no scrollbars appear, and only a portion of the image is displayed. I'll post some code excerpts below so you can get an idea of what I'm doing.
The JPanel subclass
public class xImagePanel extends JPanel { BufferedImage image; public xImagePanel(){ image = null; this.setAutoscrolls(true); } public void setImage(String path) throws IOException{ File f = new File(path); image = ImageIO.read(f); } @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.drawImage(image, 0,0, this); } }
And the main class where it is added to the scrollpane. I didn't add the entire class because the scrollpane is part of a much larger GUI.
try { JScrollPane jScrollPane1 = new JScrollPane(); xImagePanel imagePanel = new xImagePanel(); imagePanel.setSize(2560, 1600); imagePanel.setImage("...\testIMG.jpg"); //directory path excluded } catch (IOException ex) { Logger.getLogger(xbsMainFrame.class.getName()).log(Level.SEVERE, null, ex); } jScrollPane1.getViewport().add(imagePanel);