-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJListDemo.java
More file actions
48 lines (45 loc) · 1.63 KB
/
Copy pathJListDemo.java
File metadata and controls
48 lines (45 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListDemo implements ListSelectionListener {
JFrame f = new JFrame("JList Demo");
JList<String> jlst;
JLabel l;
JScrollPane p;
//creating an array of cities
String cities[]={"Kathmandu","Pokhara","Hetauda","Birgunj",
"Dharan","Biratnagar","Butwal","Dhangadhi","Nepalgunj",
"Damak","Dharan","Bharatpur","Janakpur","Itahari"};
void makeGUI(){
jlst = new JList<String>(cities);
//setting the list selection mode
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//adding the list to scroll pane
p = new JScrollPane(jlst);
//setting size of scroll pane
p.setSize(150, 200);
//making label that displays the selection
l = new JLabel("Choose a city");
//adding selection listener for the list
jlst.addListSelectionListener(this);
//adding scroll pane and label to frame
f.add(p);f.add(l);
f.setSize(400, 500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//handling list selection event
public void valueChanged(ListSelectionEvent lse){
//get the index of the changed item
int idx = jlst.getSelectedIndex();
//display selection if item was selected
if(idx!=-1)
l.setText("Current City : "+cities[idx]);
else
l.setText("Choose a city");
}
public static void main(String[] args) {
JListDemo jd = new JListDemo();
jd.makeGUI();
}
}