簡體   English   中英

如何使包含Jpanel的Jframe可滾動?

[英]How to make a Jframe containing a Jpanel scrollable?

因此,我有一個包含JPanel的JFrame,並在其中添加了具有所需信息的JLabel,但由於我一直都會在某些時候添加標簽,因此文本太長而無法顯示,因此我想添加滾動條。 基本上,我想使帶有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
}

}

contentPane.setLayout(null);

不要使用空布局!!!

您需要使用適當的布局管理器。 閱讀有關布局管理器的Swing教程中的部分,以獲取更多信息和工作示例。 然后,在將組件添加到面板時,布局管理器將確定面板的首選大小。

必要時,滾動窗格將顯示滾動條。

如果將組件動態添加到面板(在可見GUI之后),則代碼應類似於:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM