Java Swing:未使用JScrollPane添加到JPanel的组件

时间:2014-12-15 08:50:41

标签: java swing jpanel jscrollpane tablelayout

这段代码只是一个愚蠢的例子,我需要了解解决我正在处理的另一个项目的更大问题:正如你所看到的,在for循环中,23个按钮应该被添加到JPanel。因为它们无法一起显示所以我决定添加一个JScrollPane,但发生了一件奇怪的事情:只显示了19个,我不明白为什么。大小矩阵有1列23行,所以它是正确的。你知道为什么会这样吗?感谢

package proveGUI;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import layout.TableLayout;

public class Main {

  public static void main(String argv[]) {

      JFrame jframe = new JFrame("Protocollo UTL");
      //jframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
      jframe.setSize(1200, 450);

      JPanel body = new JPanel();
      double[][] size = {
              {0.05},
              {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}

      };

      body.setLayout(new TableLayout(size));

      for(int i=0; i<22; i++) {
          body.add(new JButton(String.valueOf(i)), "0,"+String.valueOf(i));
      }

      JScrollPane scrollPane = new JScrollPane(body,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

      jframe.add(scrollPane);
      jframe.setVisible(true);

  }

}

enter image description here

2 个答案:

答案 0 :(得分:2)

我对TableLayout了解不多,因为我没有使用它。如果这是您第一次使用Swing,请尝试使用common Swing Layouts

对于您的情况,您可以简单地尝试

body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); // instead of TableLayout

当您了解布局如何在Swing中工作时,请使用GridBagLayout,因为它是最可调整的布局。

答案 1 :(得分:2)

问题源于您使用介于0.00和1.00之间的大小值。这些被解释为相对大小/百分比,在这种情况下为5%。这就是为什么它只显示20行(0到19)。尝试使用&#34; 50.0&#34;相反,问题就消失了。或者使用TableLayout.PREFERRED