Advertisement
rohitmehra

Untitled

Dec 17th, 2012
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. // Demonstrate JList.
  2. import javax.swing.*;
  3. import javax.swing.event.*;
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. /*
  7. <applet code="JListDemo" width=200 height=120>
  8. </applet>
  9. */
  10. public class JListDemo extends JApplet {
  11. JList jlst;
  12. JLabel jlab;
  13. JScrollPane jscrlp;
  14. // Create an array of cities.
  15. String Cities[] = { "New York", "Chicago", "Houston",
  16. "Denver", "Los Angeles", "Seattle",
  17. "London", "Paris", "New Delhi",
  18. "Hong Kong", "Tokyo", "Sydney" };
  19. public void init() {
  20. try {
  21. SwingUtilities.invokeAndWait(
  22. new Runnable() {
  23. public void run() {
  24. makeGUI();
  25. }
  26. }
  27. );
  28. } catch (Exception exc) {
  29. System.out.println("Can't create because of " + exc);
  30. }
  31. }
  32. private void makeGUI() {
  33. // Change to flow layout.
  34. setLayout(new FlowLayout());
  35. // Create a JList.
  36. jlst = new JList(Cities);
  37. // Set the list selection mode to single selection.
  38. jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  39. // Add the list to a scroll pane.
  40. jscrlp = new JScrollPane(jlst);
  41. // Set the preferred size of the scroll pane.
  42. jscrlp.setPreferredSize(new Dimension(120, 90));
  43. // Make a label that displays the selection.
  44. jlab = new JLabel("Choose a City");
  45. // Add selection listener for the list.
  46. jlst.addListSelectionListener(new ListSelectionListener() {
  47. public void valueChanged(ListSelectionEvent le) {
  48. // Get the index of the changed item.
  49. int idx = jlst.getSelectedIndex();
  50. // Display selection, if item was selected.
  51. if(idx != -1)
  52. jlab.setText("Current selection: " + Cities[idx]);
  53. else // Otherwise, reprompt.
  54. jlab.setText("Choose a City");
  55. }
  56. });
  57. // Add the list and label to the content pane.
  58. add(jscrlp);
  59. add(jlab);
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement