JList 左连接和填充

JList Left Attached and Filled

    setLayout(new BorderLayout());
    add(listScroller, BorderLayout.WEST);

当我这样做时,我的列表被附加并填充了所有列大小。但是当我添加更多东西时。

    setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();

    gc.gridx = 2;
    gc.gridy = 0;
    add(nameLabel, gc);

它变小了,当我调整大小时它变得不可见。我怎样才能让列表在左边,其他东西在右边。

附加问题:如果列表中的元素很少,我的滚动条不会显示。不管发生什么我都想看滚动条。

首先,您可能希望使用单个布局管理器...

setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();

gc.gridx = 0;
gc.gridy = 0;
gc.weighty = 1;
gc.fill = GridBagConstraints.BOTH;
gc.gridheight = GridBagConstraints.REMAINDER;
add(listScroller, gc);

gc.gridx = 2;
gc.gridy = 0;
gc.weighty = 0;
gc.fill = GridBagConstraints.NONE;
gc.gridheight = 1;
add(nameLabel, gc);

setLayout(new BorderLayout());
add(listScroller, BorderLayout.WEST);
add(nameLabel);

取决于你想要达到的目标

有关详细信息,请参阅 Laying Out Components Within a Container

Extra question: If there is few elements in list, my scroller doesn't show. I wanna see scroller whatever happens.

你会想看一看 JScrollPane#setVerticalScrollBarPolicy and JScrollPane#setHorizontalScrollBarPolicy