2015-10-07 68 views
0

我創建了兩個面板和一個主面板。每個面板都包含一個非常大的圖像,我希望它們都能夠滾動查看圖像的其餘部分。但是,當我在主面板中添加兩塊面板並運行它時,第一塊麪板非常大以至於它覆蓋了第二塊面板。我將如何爲兩個面板實現ScrollPane?使用多個面板滾動窗格

import java.awt.BorderLayout; 
import javax.swing.*; 

public class BoardFrame extends JFrame { 

    JPanel mainPanel = new JPanel(new BorderLayout()); 

    JLabel jLabel = new JLabel(); 
    JPanel jPanelNorth = new JPanel(); 
    JScrollPane scrollPane = new JScrollPane(); 

    JLabel jLabel2 = new JLabel(); 
    JPanel jPanelSouth = new JPanel(); 
    JScrollPane scrollPane2 = new JScrollPane(); 

    public BoardFrame() { 
     jLabel.setIcon(new ImageIcon("an image here")); 
     jPanelNorth.add(jLabel); 

     jLabel2.setIcon(new ImageIcon("an image here")); 
     jPanelSouth.add(jLabel2); 

     mainPanel.add(jPanelNorth, BorderLayout.NORTH); 
     mainPanel.add(jPanelSouth, BorderLayout.SOUTH); 

     add(mainPanel); 


     //where would I use this? 
     //scrollPane.setViewportView(); 

    } 
} 

回答

2

每個面板包含一個非常大的圖像>

//JPanel mainPanel = new JPanel(new BorderLayout()); 
JPanel mainPanel = new JPanel(new GridLayout(0, 1)); 

您可能需要使用一個網格佈局,使每個滾動窗格中佔據了一半的框架,從而顯示儘可能多的每個圖像。

//JScrollPane scrollPane = new JScrollPane(); 
JScrollPane scrollPane2 = new JScrollPane(jPanelNorth); 

使用滾動窗格中的最簡單的方法是創建你想顯示和滾動面板將組件添加到視你的組件滾動窗格。

//mainPanel.add(jPanelNorth, BorderLayout.NORTH); 
    mainPanel.add(scrollPane); // don't need the constraint when using GridLayout. 

然後添加滾動面板的主面板,因爲滾動面板包含圖像的面板。

+0

謝謝你洙多。這正是我想要做的!可以理解和正確的點!再次感謝 :)!! – Jake

0

似乎使用的網格佈局比使用邊框佈局,在這種情況下要好得多:

import java.awt.BorderLayout; 
import javax.swing.*; 

public class BoardFrame extends JFrame { 
//1. use GridLayout with 2 rows and 1 column . 
JPanel mainPanel = new JPanel(new GridLayout(2,1)); 

JLabel jLabel = new JLabel(); 
JPanel jPanelNorth = new JPanel(); 
JScrollPane scrollPane = new JScrollPane(); 

JLabel jLabel2 = new JLabel(); 
JPanel jPanelSouth = new JPanel(); 
JScrollPane scrollPane2 = new JScrollPane(); 

public BoardFrame() { 
    jLabel.setIcon(new ImageIcon("an image here")); 
    jPanelNorth.add(jLabel); 

    jLabel2.setIcon(new ImageIcon("an image here")); 
    jPanelSouth.add(jLabel2); 


    //2.you should place .setViewportView() here : 
    scrollPane.setViewportView(jPanelNorth); 
    scrollPane2.setViewportView(jPanelSouth); 


    mainPanel.add(scrollPane);//is in the top ("North") 
    mainPanel.add(scrollPane2);//next ("South") 

    //3.use setContentPane instead of add() 
    setContentPane(mainPanel); 




} 
}