我的JPanel
里面加了JList
。如何使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我有toString()
个函数返回样本String
答案 0 :(得分:2)
jPanel.setLayout(new BorderLayout());
jPanel.add(jList, BorderLayout.CENTER);
答案 1 :(得分:1)
试试这个..
JList<String> list = new JList<>();
JPanel panel = new JPanel(new BorderLayout());
panel.add(list,BorderLayout.CENTER);
如果面板中有单个组件,则会自动拉伸组件。
答案 2 :(得分:1)
如何使JList像我的JPanel一样获得身高和体重。 它需要完全填充它。
在这种情况下,解决方案是将列表添加到带有BorderLayout的JPanel
中,如其他答案所述。
如果我的JList中有2个项目,我希望其中1个是1/2 高度,如果高度为3 - 1/3等。
这个要求有点棘手:单元格高度取决于列表的可见矩形和列表中元素的数量或要显示的元素数量,可能会有所不同。
例如,假设列表有6个元素,但您只想显示最多5个单元格(行),然后滚动列表。您可以执行以下操作:
例如:
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());
}
});