Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created May 17, 2018 14:55
Show Gist options
  • Save yukeehan/d35f88fdcc7a23d8b9d5ca943db2da86 to your computer and use it in GitHub Desktop.
Save yukeehan/d35f88fdcc7a23d8b9d5ca943db2da86 to your computer and use it in GitHub Desktop.
Swing JList
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class ListDemo implements ListSelectionListener {
JList<String> jlst;
JLabel jlab;
JScrollPane jscrlp;
String names[]= { "Yukee", "Jon", "Mountain", "Harry", "Ken", "Halen", "Tom", "Jerry" };
ListDemo(){
JFrame jfrm = new JFrame("Jlist Demo");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(200, 160);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlst = new JList<String>(names);
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jscrlp = new JScrollPane(jlst);
jscrlp.setPreferredSize(new Dimension(120, 90));
jlab = new JLabel("Please choose a name");
jlst.addListSelectionListener(this);
jfrm.add(jscrlp);
jfrm.add(jlab);
jfrm.setVisible(true);
}
//Handle list selection events
public void valueChanged(ListSelectionEvent le) {
int idx = jlst.getSelectedIndex();
if(idx != -1)
jlab.setText("Current selection: " + names[idx]);
else
jlab.setText("Please choose a name");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ListDemo();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment