2009-11-06 53 views
3

我有這個小程序顯示在apanel ..圖像,但我無法滾動添加到它..這是我的代碼添加JScrollPane的在面板上顯示的圖像

的類擴展JPanel以顯示圖像:

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; 

}

並且具有另一個名爲imageContainer面板以保持表示面板的主框架的一個示例:

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); 


} 

那麼我在這裏做了什麼錯誤?

回答

6

當添加到滾動窗格的組件的首選大小超出滾動窗格的大小時,滾動條會自動出現。您的自定義面板沒有首選大小,所以滾動條從不出現。一種解決方案是隻返回一個首選的大小等於圖像的大小。

當然,我永遠無法理解爲什麼人們去所有的麻煩做這類風俗畫的。不需要定製類。只需從BufferedImage創建一個ImageIcon,然後將該圖標添加到JLable,然後將該標籤添加到滾動窗格中,並且不會出現任何這些問題。進行自定義繪畫的唯一原因是如果您需要縮放圖像或提供其他奇特效果。

+0

謝謝..以及我也會在圖像 – CiCi 2009-11-06 20:31:12

+0

上做scalnig和ather事情,但即使是縮放也可以通過覆蓋JLabel上的「paint」方法來處理 – aperkins 2009-11-06 21:23:27

1

因爲「imagecontainer」是被添加到您的滾動面板類,這是一個需要超過一定的尺寸,使事情滾動面板。你應該把'showPanel'直接放到可縮放的容器中。

+0

所以這樣做的代碼是正確的? JScrollPane scroller = new JScrollPane(showPanel); (new Dimension(image.getWidth(),image.getHeight()));imageContainer.add(showPanel); 但我仍然gettig什至沒有圖像顯示! – CiCi 2009-11-06 20:20:45