簡體   English   中英

如何使JList填充JPanel

[英]How to make a JList filling 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類中的Samolot我有toString()函數返回樣本String

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一樣獲得身高和體重。 它需要完全填補它。

那么在這種情況下,解決方案是將列表添加到具有BorderLayoutJPanel ,如其他答案中所指出的。

如果我的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());
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM