[英]Java Swing: components not added to JPanel with JScrollPane
This code is just a silly example which I need to understand to solve a much bigger problem about another project I am working on: as you can see, in the for cycle, 23 buttons are supposed to be added to JPanel. 这段代码只是一个愚蠢的例子,我需要了解解决我正在处理的另一个项目的更大问题:正如你所看到的,在for循环中,23个按钮应该被添加到JPanel。 As they cannot be shown all together I decided to add a JScrollPane but a strange thing happens: only 19 are shown and I do not understand why.
因为它们无法一起显示所以我决定添加一个JScrollPane,但发生了一件奇怪的事情:只显示了19个,我不明白为什么。 The size matrix has 1 column for 23 rows so it is correct.
大小矩阵有1列23行,所以它是正确的。 Do you know why this happens?
你知道为什么会这样吗? Thanks
谢谢
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);
}
}
I don't know much about TableLayout
because I've didn't ever use it. 我对
TableLayout
了解不多,因为我没有使用它。 If it is your first experience with Swing, try the common Swing Layouts . 如果这是您第一次体验Swing,请尝试常见的Swing Layouts 。
For your case, you can simple try 对于您的情况,您可以简单一试
body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); // instead of TableLayout
When U'll understand how layouts work in Swing, use GridBagLayout
, because it is the most adjustable layout. 当你将了解布局如何在Swing中工作时,使用
GridBagLayout
,因为它是最可调整的布局。
The problem stems from you using size values between 0.00 and 1.00. 问题源于您使用介于0.00和1.00之间的大小值。 These are interpreted as relative sizes/percentages, in this case 5%.
这些被解释为相对大小/百分比,在这种情况下为5%。 That's why it's showing 20 rows only (0 to 19 inclusive).
这就是为什么它只显示20行(0到19)。 Try using "50.0" instead and the problem goes away.
尝试使用“50.0”代替,问题就消失了。 Or use
TableLayout.PREFERRED
. 或者使用
TableLayout.PREFERRED
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.