提问者:小点点

如何让一个包含Jpanel的Jframe可滚动?


所以我有一个包含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个答案

匿名用户

contentPane.setLayout(null);

不要使用空布局!!!

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

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

如果将组件动态添加到面板(在 GUI 可见之后),则代码应如下所示:

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