我正在尝试在容器中实现JPanel列表。出于某种原因,我无法将面板对齐到顶部
gbc.anchor = GridBagConstraints.NORTH; gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTH; gbc.weighty = 0;
正如您所看到的,对齐顶部仅适用于重量> 0
以下列方式创建容器:
public ListSection()
{
setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) );
mainList = new JPanel( new GridBagLayout() );
mainList.setBorder( BorderFactory.createLineBorder( Color.cyan, 2 ) );
JScrollPane scrollPane = new JScrollPane( mainList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
scrollPane.setBorder( null );
scrollPane.setVerticalScrollBar( new HScrollBar() );
add( scrollPane );
}
然后从另一个类调用它:
mainListSection = new ListSection( );
messagesContainer.add( mainListSection );
正在添加JPanels:
public static void addToMainList( List<Message> messages )
{
mainListSection.getMainList().removeAll();
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.BOTH;
for( Message message : messages )
{
if( Toolbar.getFilterParameter().equals( "all" ) )
{
JPanel panel = MessageBlock.buildBlock( message );
mainListSection.getMainList().add( panel, gbc );
}
else
{
if( Toolbar.getFilterParameter().equals( "catalogue" ) &&
( message.type.equals( "users" ) || message.type.equals( "userpersonals" ) ) )
{
JPanel panel = MessageBlock.buildBlock( message );
mainListSection.getMainList().add( panel, gbc );
}
else if( Toolbar.getFilterParameter().equals( message.type ) )
{
JPanel panel = MessageBlock.buildBlock( message );
mainListSection.getMainList().add( panel, gbc );
}
}
}
mainListSection.validate();
mainListSection.repaint();
}
因此,当我尝试将weighty设置为0时会出现问题。这会将垂直对齐设置为居中。
如果能以某种方式解决这个问题,可以请任何人提出建议吗?
提前致谢
修改
在MadProgrammer的帮助下,我设法解决了这个问题。我所要做的就是将weighty = 1设置为循环中的最后一项。所以更新后的代码如下:
public static void addToMainList( List<Message> messages )
{
mainListSection.getMainList().removeAll();
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
int i = 1;
for( Message message : messages )
{
gbc.weighty = ( i != messages.size() ) ? 0 : 1;
if( Toolbar.getFilterParameter().equals( "all" ) )
{
JPanel panel = MessageBlock.buildBlock( message );
mainListSection.getMainList().add( panel, gbc );
}
else
{
if( Toolbar.getFilterParameter().equals( "catalogue" ) &&
( message.type.equals( "users" ) || message.type.equals( "userpersonals" ) ) )
{
JPanel panel = MessageBlock.buildBlock( message );
mainListSection.getMainList().add( panel, gbc );
}
else if( Toolbar.getFilterParameter().equals( message.type ) )
{
JPanel panel = MessageBlock.buildBlock( message );
mainListSection.getMainList().add( panel, gbc );
}
}
i++;
}
mainListSection.validate();
mainListSection.repaint();
}