2016-05-04 46 views
0

所以我有這個JFrame,它包含一個JPanel,並且在那裏我添加了JLabels和我想要的信息,但是因爲我一直在添加標籤,所以文本太長了,所以我想添加一個滾動條。基本上我想讓JFrame帶有一個可滾動的JPanel。我有這個代碼,但我的問題是,即使滾動條出現,但它不會移動,並且當文本很多時不起作用,這意味着文本仍然被剪切掉,滾動條沒有移動。有誰知道如何解決這一問題?如何製作包含Jpanel滾動條的Jframe?

import javax.swing.*; 
import java.awt.*; 
import java.util.*; 
public class Bar { 
JFrame info = new JFrame("Information"); 
JLabel ballinf = new JLabel(); 
JPanel contentPane = new JPanel(); 
JScrollPane scrolling = new JScrollPane(); 

public Bar(){ 
    contentPane.setOpaque(true); 
    contentPane.setBackground(Color.WHITE); 
    contentPane.setLayout(null); 

    scrolling = new JScrollPane(contentPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 

    info.add(scrolling); 
    info.setSize(750, 600); 
    info.setLocationByPlatform(true); 
    info.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    info.setVisible(true); 
} 

public void adding(int pos){  
    ballinf = new JLabel("Something ",JLabel.CENTER);//assume the text will be bigger here and have more info 
    ballinf.setSize(700, 30); 
    ballinf.setForeground(Color.green); 
    ballinf.setLocation(5, 5+pos); 
    contentPane.add(ballinf); 

    info.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    info.setVisible(true); 
    } 

public static void main(String[] args){ 
    Bar stats = new Bar(); 
    stats.adding(0); 
    stats.adding(20);//this will be done in a for loop for more than 2 times so the text ends up to be a lot 
} 

}

回答

3
contentPane.setLayout(null); 

不要使用空佈局!

您需要使用合適的佈局管理器。有關更多信息和工作示例,請參閱Layout Managers上的Swing教程部分。隨後,在向面板添加組件時,佈局管理器將確定面板的首選大小。

滾動面板將在必要時顯示滾動條。

如果動態組件添加到面板(後GUI是可見的),則代碼應該是這樣的:

panel.add(...); 
panel.revalidate(); 
panel.repaint(); 
+0

,應重新驗證和重繪被稱爲? – DarkV1

+0

那麼我應該刪除setLayout(null)命令? – helpme

+0

@helpme,你試過了嗎? – camickr