views:

279

answers:

2

i have this little program for showing images on apanel.. but i'm not able to add a scroll to it.. and this is my code

the class that extends jpanel to show the image:

public class ShowPanel extends JPanel{

public ShowPanel(BufferedImage image, int height, int width) {
  this.image = image;
  this.height = height;
  this.width = width;
  //this.setBounds(width, width, width, height);

}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, height, width, null);
}

public void setImage(BufferedImage image, int height, int width) {
    this.image = image;
    this.height = height;
    this.width = width;

}

private BufferedImage image;
private int height;
private int width;

}

and a sample of the main Frame that has another panel called imageContainer to hold the showing panel:

public class MainFrame extends javax.swing.JFrame {

/** Creates new form MainFrame */
public MainFrame() {
    initComponents();
    image = null;
    path = "PantherOnLadder.gif";
    image = Actions.loadImage(path);
    showPanel = new ShowPanel(image, 0, 0);
    spY = toolBar.getY() + toolBar.getHeight();
    showPanel.setBounds(0, spY, image.getWidth(), image.getHeight());
    showPanel.repaint();
    imageContainer.add(showPanel);
    JScrollPane scroller = new JScrollPane(imageContainer);
    scroller.setAutoscrolls(true);


}

so what's the mistake i did here ?

+1  A: 

Since the 'imagecontainer' is the class being added to your scrollable panel, that is the panel which needs to exceed a certain size to make things scrollable. You should place the 'showPanel' directly into a scollable container.

yankee2905
so is it right to make the code like this?JScrollPane scroller = new JScrollPane(showPanel);scroller.setPreferredSize(new Dimension(image.getWidth(),image.getHeight() ));imageContainer.add(showPanel);but I'm still gettig nothing even the image isn't showing !!
Razan
+2  A: 

The scrollbars appear automatically when the preferred size of the component added to the scrollpane exceeds the size of the scroll pane. Your custom panel doesn't have a preferred size so the scrollbars never appear. One solution is to just return a preferred size equal to the size of the image.

Of course I never understand why people go to all the trouble to do this type of custom painting. There is no need for a custom class. Just create an ImageIcon from the BufferedImage and then add the Icon to a JLable and then add the label to the scrollpane and you won't have any of these problems. The only reason to do custom painting is if you need to scale the image or provide some other fancy effect.

camickr
thanks.. well I will also do scalnig and ather things on the image
Razan
but even the scaling can be handled just by overriding the "paint" method on the JLabel
aperkins