【问题标题】:How to make a Jframe containing a Jpanel scrollable?如何使包含 Jpanel 的 Jframe 可滚动?
【发布时间】:2016-05-04 21:50:24
【问题描述】:

所以我有一个包含 JPanel 的 JFrame,并在其中添加了带有我想要的信息的 JLabels,但是由于我会在某些时候一直添加标签,所以文本太长而无法显示,所以我想添加一个滚动条.基本上我想让我的 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
}

}

【问题讨论】:

    标签: java swing jframe jpanel jscrollpane


    【解决方案1】:
    contentPane.setLayout(null);
    

    不要使用空布局!!!

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

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

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

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

    【讨论】:

    • 应该调用 revalidate 和 repaint 吗?
    • @helpme,你试过了吗?
    • @DarkV1 should revalidate and repaint be called? - 我说明了应该调用这些方法的条件。
    • 刚刚滚动条确实起作用了,非常感谢!但是现在我不再有布局来使文本的结构为空。。意思是在我用这个命令ballinf.setLocation(5, 5+pos); 做出正确的位置之前,但所有信息都在同一行上?你知道怎么解决吗?很抱歉在这个问题中提出另一个问题。
    • @helpme,我已经告诉你解决方案了。您需要使用适当的布局管理器。默认布局是 FlowLayout。我给了你一个关于布局管理器的 Swing 教程的链接。阅读教程并使用适当的布局管理器组合。如果你想成为一名程序员,你必须阅读。
    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2016-02-27
    相关资源
    最近更新 更多