简体   繁体   中英

How to show arraylist as a seperate jlabels in java swing?

I have an arraylist of city names and I want to show them as a bottom up jlabels. How can I do that?

   ArrayList<String> cityNames = new ArrayList<>(columnCount); 

                while(resultSet.next()){
                    int i = 1;
                       while(i <= columnCount) {
                           cityNames.add(resultSet.getString(i++));
                       }            
                }

                //Loop through cityNames as seperate Jlabels
            for(String city : cityNames){
                cityLabel.setText(city);
            }

To create multiple JLabel s and add them to a panel

JPanel panel = [...];
ArrayList<String> cityNames = [...];

for(String city : cityNames)
    panel.add(new JLabel(city));

If you need to do something with them later, add them to a List as well

JPanel panel = [...];
ArrayList<String> cityNames = [...];
List<JLabel> cityLabels = new ArrayList<JLabel>();

for(String city : cityNames)
{
    JLabel label = new JLabel(city);
    cityLabels.add(label);
    panel.add(label);
}

If you just want all of the city names in one JLabel (can be on multiple lines)

ArrayList<String> cityNames = [...];

String cities = "";
for(String city : cityNames)
    cities += ", " + city; //or use "<br>" for separate lines
cities = cities.substring(2); //remove the first ", "

JLabel cityLabel = new JLabel(cities); //add this to your rendering panel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM