如何制作JList填充JPanel



我有一个内部添加了JListJPanel。如何使JList获得像我的JPanel一样的身高和体重。它需要完全填满它。

如果我的JList中有2个项目,我希望其中1个是1/2的高度,如果是3-1/3的高度等。

有什么解决方案吗?

public class RozkladLotow extends JPanel{
Vector<Samolot> samoloty;
public RozkladLotow(GeneratorSamolotow g){
    super();
    this.setLayout(new BorderLayout());
    Miasto m1 = new Miasto("Warszawa",571,142,"Polska",10,10);//sample objects needed to create a `Samolot`
    Miasto m2 = new Miasto("Pekin",571,142,"Chiny",10,10);//sample objects needed to create a `Samolot`
    samoloty = new Vector<Samolot>();
    samoloty.add(new Samolot(0, m1, m2, 0, 0, 0 , 0));
    samoloty.add(new Samolot(0, m2, m1, 0, 0, 0 , 0));
    JList lista = new JList<Samolot>(samoloty);
    add(lista,BorderLayout.CENTER);     
}
}

Samolot中的Ofc我得到了返回样本StringtoString()函数

jPanel.setLayout(new BorderLayout());
jPanel.add(jList, BorderLayout.CENTER);

试试这个。。

     JList<String> list = new JList<>();
     JPanel panel = new JPanel(new BorderLayout()); 
     panel.add(list,BorderLayout.CENTER);

若面板中有一个构件,它会自动拉伸该构件。

如何让JList获得像我的JPanel一样的身高和体重。它需要完全填满它。

在这种情况下,解决方案是将列表添加到具有BorderLayout的JPanel中,正如其他答案中所指出的那样。

如果我的JList中有2个项目,我想其中1个是高度,如果是高度的3-1/3等

这个要求有点棘手:单元格高度取决于列表的可见矩形和列表中元素的数量您希望显示的元素数量,这可能会有所不同。

例如,假设列表有6个元素,但您只想显示最多5个单元格(行),然后滚动列表。您可以执行以下操作:

  • 使用JList.setVisibleRowCount()方法设置要显示的最大单元格数
  • 向列表中添加ComponentListener以侦听调整列表大小时触发的组件事件:ComponentListener.componentResized()
  • 使用JComponent.getVisibleRect()方法获取列表的可见矩形
  • 使用JList.setFixedCellHeight()方法设置固定的单元格高度

例如:

DefaultListModel model = new DefaultListModel();
model.addElement("Fender");
model.addElement("Gibson");
model.addElement("Ibanez");
model.addElement("Paul Reed Smith");
model.addElement("Jackson");
model.addElement("Godin"); // The model has 6 elements
JList list = new JList(model);
list.setVisibleRowCount(5); // I want to show only 5 elements, then scroll the list
list.addComponentListener(new ComponentAdapter() { // ComponentAdapter implements ComponentListener interface
    @Override
    public void componentResized(ComponentEvent e) {
        JList list = (JList)e.getComponent();
        int divider = Math.min(list.getVisibleRowCount(), list.getModel().getSize());
        list.setFixedCellHeight(list.getVisibleRect().height / divider);
    }
});
JPanel content = new JPanel(new BorderLayout());
content.add(new JScrollPane(list));

由于我使用Math.min()来确定最小除法器,以便正确设置固定的单元格高度,因此如果列表模型只有2个元素,它们都将填充每个可用高度的50%。

注意:如果您想始终显示列表中的所有元素,那么更容易:

list.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(ComponentEvent e) {
        JList list = (JList)e.getComponent();
        list.setFixedCellHeight(list.getVisibleRect().height / list.getModel().getSize());
    }
});

最新更新