如何使包含Jpanel的Jframe可滚动?

时间:2016-05-04 21:50:25

标签: java swing jframe jpanel jscrollpane

所以我有一个包含JPanel的JFrame,在那里我添加了JLabel我想要的信息但是因为我会在某些时候添加标签文本太长而无法显示所以我想添加滚动条。基本上我想让我的JFrame中的JPanel可滚动。我有这个代码,但我的问题是,即使滚动条出现,但它没有移动,并且在文本很多时不能真正起作用,这意味着文本仍然被删除,滚动条没有移动。有谁知道如何解决这个问题?

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
}

}

1 个答案:

答案 0 :(得分:3)

contentPane.setLayout(null);

不要使用空布局!!!

您需要使用适当的布局管理器。阅读Layout Managers上Swing教程中的部分,了解更多信息和工作示例。然后,当您向面板添加组件时,布局管理器将确定面板的首选大小。

滚动窗格将在必要时显示滚动条。

如果您动态地向面板添加组件(在GUI可见之后),那么代码应该是这样的:

panel.add(...);
panel.revalidate();
panel.repaint();
相关问题