我有一个主面板,我正在向其中动态添加组件。
主面板的 GridLayout 限制为 3 列和 0 行(0 行将允许行无限增长),但问题是我希望所有组件都具有固定大小或组件的首选大小。
如果满足我的要求,我可以使用其他布局...但目前只有 GridLayout 允许我将列限制为 3...
忘了说了,JScrollpane中添加了Main Panel,所以我可以垂直滚动。
最佳答案
实现此目的的一种方法是使用 JPanel。 GridLayout 将拉伸(stretch)您的组件,但如果您将组件包装在 JPanel 中,则 JPanel 会被拉伸(stretch)。由于 JPanel 使用不拉伸(stretch)组件的 FlowLayout,您的组件将保持其首选大小。
这是一个使用 JButton 的例子。请注意我是如何在每个循环中将它们添加到(新的)JPanel,然后将面板添加到网格布局的。
import javax.swing.*;
public class GridLayout {
public static void main( String[] args ) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setLayout( new java.awt.GridLayout( 0, 3 ) );
for( int i = 0; i < 21; i++ ) {
JPanel panel = new JPanel(); // Make a new panel
JButton button = new JButton( "Button "+i );
panel.add( button ); // add the button to the panel...
frame.add( panel ); // ...then add the panel to the layout
}
frame.pack();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
} );
}
}
关于java - 具有组件固定宽度和高度的 GridLayout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16369230/