我目前在JPanel内有一个JPanel,我想在其中放置JScrollPane / JTable。我无法将其放置在所需位置。我想让表格适合JPanel的整个宽度,但只填满它所需的空间,以便在表格中垂直显示所有动态数据。

这是我目前拥有的代码,图片就是它的样子。蓝色区域是表格/滚动情况的嵌套面板。还有为什么桌子下面有一个愚蠢的灰色盒子。我该如何摆脱呢?抱歉,图片是敏感数据。谢谢。

    JPanel panel = new JPanel();
    panel.setBounds(50, 100, 300, 450);
    panel.setBackground(Color.blue);
    contentPane.add(panel); //contentPane is the outter panel

    JScrollPane scrollpane = new JScrollPane(table); //table was created earlier
    panel.add(scrollpane,BorderLayout.NORTH);




示例程序(我不要桌子底下的那个大矩形)

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Test {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(350,100,1000,800);
    JPanel contentPane = new JPanel(new BorderLayout());
    frame.setContentPane(contentPane);
    JTable table = new JTable(5,5);
    JScrollPane scrollpane = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    contentPane.add(scrollpane,BorderLayout.NORTH);
    frame.revalidate();
}

}

最佳答案

还有为什么桌子下面有一个愚蠢的灰色盒子。我该如何摆脱
  其中?


table.setFillsViewportHeight(true);添加到JSCrollPane后,尝试使用它:

   JPanel panel = new JPanel();
   // other code
   panel.setLayout(new BorderLayout()); // not sure whither you are already doing this

   JScrollPane scrollPane = new JScrollPane(table);
   table.setFillsViewportHeight(true);

   panel.add(scrollPane, BorderLayout.CENTER);


调用setFillsViewportHeight(true)函数设置fillsViewportHeight属性。当此属性为true时,即使table没有足够的行来使用整个垂直空间,table也会使用容器的整个高度。

注意:


我看不到您在panel中添加了JScrollPane的布局。我希望您知道JPanel使用FlowLayout作为其默认布局,该布局遵循组件的首选大小提示。同样,panel.add(scrollpane, BorderLayout.NORTH);产生歧义。当我们使用约束:BorderLayout.NORTH到具有BorderLayout作为其布局管理器的组件时。
框架的内容窗格具有BorderLayout作为其默认的布局管理器。您正在使用panel设置绑定到setBounds(),这通常是在处理AbsoluteLayout(null)布局时执行的。而在Swing中开发应用程序时AbsoluteLayout绝不可行

关于java - 可滚动表的Java Swing布局?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19939293/

10-13 07:48
查看更多