为什么我没有获得正常运行的JScrollPane?

时间:2012-08-28 08:44:29

标签: java swing layout user-interface jscrollpane

我有一个JFrame窗口,我想在它的中间添加一个可滚动的JTable。我有一个名为collectionTableScrollPane()的方法生成JScrollPane(我知道这可以保证有效)。

然后我继续将其添加到我的mainPanel面板中。但是,我希望在JScrollPane的左侧和右侧有一些强制30px填充。从逻辑上讲,我会创建一个以JPanel为中心的FlowLayout,并在Box.createHorizontalStrut(30)的任意一侧添加JScrollPane

JPanel tableHolderPanel = new JPanel(new FlowLayout());
mainPanel.add(tableHolderPanel);
tableHolderPanel.add(Box.createHorizontalStrut(30));
tableHolderPanel.add(collectionTableScrollPane());
tableHolderPanel.add(Box.createHorizontalStrut(30));

然而,我得到一个奇怪的结果,窗口中间的JScrollPane(用箭头表示)有点变得无效。

有谁知道问题是什么?

1

请注意,JTable包含四行,其中只有两行可见。

3 个答案:

答案 0 :(得分:3)

过去我在JScrollPane面板中使用FlowLayout时遇到了一些问题。行为可能很棘手,当内容增长时,可能会出现水平滚动条,或者FlowLayout应该添加一个新行。

在您的情况下,我会将FlowLayout替换为BorderLayout

JPanel tableHolderPanel = new JPanel(new BorderLayout());
mainPanel.add(tableHolderPanel);
tableHolderPanel.add(Box.createHorizontalStrut(30), BorderLayout.WEST);
tableHolderPanel.add(collectionTableScrollPane(), BorderLayout.CENTER);
tableHolderPanel.add(Box.createHorizontalStrut(30), BorderLayout.EAST);

答案 1 :(得分:2)

据我所知,Box假设与BoxLayout一起使用,这可能会导致一些问题。相反,为什么不在tableHolderPane

上使用EmptyBorder

答案 2 :(得分:1)

BoxLayout接受来自JComponents的尺寸,与FlowLayout预先实现的默认JPanel相同的问题

  1. 您必须通过覆盖PreferredSize嵌套JPanel

  2. 返回JScrollPane
  3. 使用其他LayoutManager,例如GridBagLayout或今天MigLayout

  4. 使用NestedLayout,使用BorderLayoutJLabel(ei返回PreferredSize)放入EAST和{{} 1}}区域

  5. 一切都取决于你是否真的要创建空白区域并且是否可以重新获取