2016-05-04 39 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