How can I display an arraylist in a JList?

Lachlan Williamson :

I want to display the all the details of elements in arraylist bikes in a Jlist. I've been trying to figure out how to do this for a while but I just can't crack it. The Jlist is part of a panel called pnlBikesTab.

ArrayList and JList

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

Populating Arraylist

 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) ;
}

Main

 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);
    }
John Joe :

@daniu is right. You can use this

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

Another thing is that bikes will always return size 0 in BikeNowGUI because you are calling BikeNowGUI first before Initial method. I would suggest you move all the code to Initial method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156490&siteId=1