如何在 JList 中显示数组列表?

How can I display an arraylist in a JList?

我想在 Jlist 中显示 arraylist bikes 中元素的所有详细信息。一段时间以来,我一直在试图弄清楚如何做到这一点,但我就是无法破解它。 Jlist 是名为 pnlBikesTab 的面板的一部分。

ArrayList 和 JList

 ArrayList<Bike> bikes = new ArrayList<Bike>();
 JList<String> lstBikes ;

填充数组列表

 public void Intial(){
//Add 12 bikes  
 Bike b1 = new Bike(1, "Mountain", 12, "Not available") ;       
    Bike b2 = new Bike(2, "Road", 10, "Available") ;         
    Bike b3 = new Bike(3, "City", 8, "Available") ; 
    Bike b4 = new Bike(4, "Mountain", 12, "Available") ;   
    Bike b5 = new Bike(5, "Road", 10, "Available") ;    
    Bike b6 = new Bike(6, "City", 8, "Available") ;        
    Bike b7 = new Bike(7, "Mountain", 12, "Available") ;
    Bike b8 = new Bike(8,"Road", 10, "Available") ;
    EBike b9 = new EBike(9, "eBike", 18, "Not available", "Full Power") ;
    EBike b10 = new EBike(10, "eBike", 18, "Available", "Full Power");
    EBike b11 = new EBike(11, "eBike", 14, "Available", "Power Assist") ;
    EBike b12 = new EBike(12, "eBike", 14, "Available", "Power Assist") ;
    bikes.add(b1) ;
    bikes.add(b2) ;
    bikes.add(b3) ;
    bikes.add(b4) ;
    bikes.add(b5) ;
    bikes.add(b6) ;
    bikes.add(b7) ;
    bikes.add(b8) ;
    bikes.add(b9) ;
    bikes.add(b10) ;
    bikes.add(b11) ;
    bikes.add(b12) ;
}

主要

 public static void main(String[] args){
        BikeNowGUI fr = new BikeNowGUI();
        fr.Intial();
        fr.setTitle("Bikes") ; 
        fr.setLocationRelativeTo(null); //Center frame
        fr.setSize(300, 500);
        fr.setVisible(true);
    }

GUI

public BikeNowGUI(){
        tabs = new JTabbedPane() ; 
        //BikesTab Panel  
        pnlBikesTab = new JPanel() ;
        lblBikes = new JLabel("Bikes") ; 
        pnlBikesTab.add(lblBikes) ;
        lblImages = new JLabel(icons[0]) ;
        pnlBikesTab.add(lblImages) ;
        //Jlist
        ArrayList<Bike> bikes = new ArrayList<Bike>();
        Bike[] items = new Bike[bikes.size()];
        bikes.toArray(items);
        lstBikes = new JList(items);
        pnlBikesTab.add(lstBikes) ;
        tabs.add("Bikes", pnlBikesTab) ;

        //CustomersTab Panel
        pnlCustomersTab = new JPanel();
        tabs.add("Customers", pnlCustomersTab) ;

        //RentsTab Panel
        pnlRentsTab = new JPanel(); 
        tabs.add("Rents", pnlRentsTab) ;

        add(tabs);
    }

@daniu 说的对。你可以使用这个

lstBikes = new JList(bikes.toArray());

另一件事是,自行车在 BikeNowGUI 中总是 return 尺寸 0,因为您在 Initial 方法之前先调用 BikeNowGUI。我建议您将所有代码移至 Initial 方法。