2017-04-05 74 views
0

hy,我試圖添加多個jbuttons到窗格並想滾動它們。 所以我所做的是首先向jpanel添加按鈕,而不是jscrollpane的jpanel,而不是jscrollpane添加到另一個jpanel的按鈕等等。 但我得到的是一個按鈕顯示,但沒有滾動條滾動窗格,並看到所有的按鈕。如何將jbuttons添加到jscrollpane

import java.awt.*; 

import javax.swing.*; 

import java.awt.event.*; 

class ICFTWindow extends JFrame 

{ 
JPanel mainPanel,userlistPanel,chatPanel,userlistPanel2; 
JButton checkButton,button2,button3,button4,button5,button6; 
JScrollPane scrollpane; 
JScrollBar scrollbar; 

ICFTWindow() 
{ 
    mainPanel = new JPanel(); 
    mainPanel.setLayout(null); 

    userlistPanel = new JPanel(new FlowLayout()); 
    userlistPanel.setBounds(0,0,160,270); 
    userlistPanel2 = new JPanel(); 
    userlistPanel2.setBounds(0,0,100,270); 
    userlistPanel2.setLayout(new BorderLayout()); 

    scrollpane = new JScrollPane(userlistPanel); 

    checkButton = new JButton(); 
    checkButton.setPreferredSize(new Dimension(90, 50)); 

    button2 = new JButton(); 
    button2.setPreferredSize(new Dimension(90, 50)); 

    button3 = new JButton(); 
    button3.setPreferredSize(new Dimension(90, 50)); 

    button4 = new JButton(); 
    button4.setPreferredSize(new Dimension(90, 50)); 

    button5 = new JButton(); 
    button5.setPreferredSize(new Dimension(90, 50)); 

    button6 = new JButton(); 
    button6.setPreferredSize(new Dimension(90, 50)); 

    userlistPanel.setBorder(BorderFactory.createLineBorder(Color.black)); 

    scrollpane.add(userlistPanel); 
    mainPanel.add(userlistPanel); 

    userlistPanel.add(button2); 
    userlistPanel.validate(); 
    userlistPanel.add(checkButton); 
    userlistPanel.validate(); 
    userlistPanel.add(button3); 
    userlistPanel.validate(); 
    userlistPanel.add(button4); 
    userlistPanel.validate(); 
    userlistPanel.add(button5); 
    userlistPanel.validate(); 
    userlistPanel.add(button6); 
    userlistPanel.validate(); 

    userlistPanel.validate(); 
    userlistPanel2.add(scrollpane); 
    mainPanel.add(userlistPanel2); 
    add(mainPanel); 
    setSize(500,300); 
    setVisible(true); 

} 

public static void main(String args[]) 
{ 
    new ICFTWindow(); 
} 
} 

回答

0

刪除這兩條線:

scrollpane.add(userlistPanel); 
mainPanel.add(userlistPanel); 

你並不需要添加JPanel(您要滾動條)的JScrollPane。發送它到滾動窗格的構造函數就足夠了。

之後,您必須將滾動窗格添加到頂層組件,它還會添加包含在其中的面板並在其上放置滾動條。有關如何使用滾動窗格的更多詳細信息,請參見here