如何在JList中显示arraylist?

时间:2019-05-26 07:41:40

标签: java arraylist jlist

我想在Jlist中显示arraylist自行车中元素的所有详细信息。我一直在试图弄清楚如何做到这一点,但我只是无法破解。 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);
    }

1 个答案:

答案 0 :(得分:1)

@daniu是正确的。你可以用这个

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

另一件事是,自行车将始终在BikeNowGUI中返回大小0,因为您首先在BikeNowGUI方法之前调用Initial。我建议您将所有代码移至Initial方法。