监听JList列表项的单击事件
Posted 雨巷菰凉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了监听JList列表项的单击事件相关的知识,希望对你有一定的参考价值。
原文:http://blog.sina.com.cn/s/blog_5f1bfbd901015d5d.html
1 import java.awt.BorderLayout; 2 import java.awt.EventQueue; 3 import javax.swing.JFrame; 4 import javax.swing.JLabel; 5 import javax.swing.JList; 6 import javax.swing.JOptionPane; 7 import javax.swing.JPanel; 8 import javax.swing.JScrollPane; 9 import javax.swing.UIManager; 10 import javax.swing.border.EmptyBorder; 11 import javax.swing.event.ListSelectionEvent; 12 import javax.swing.event.ListSelectionListener; 13 public class SelectEventDemo extends JFrame { 14 15 16 private static final long serialVersionUID = -5544682166217202148L; 17 private JPanel contentPane; 18 private JList list; 19 private JLabel label; 20 21 22 public static void main(String[] args) { 23 try { 24 UIManager 25 .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 26 } catch (Throwable e) { 27 e.printStackTrace(); 28 } 29 EventQueue.invokeLater(new Runnable() { 30 public void run() { 31 try { 32 SelectEventDemo frame = new SelectEventDemo(); 33 frame.setVisible(true); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 } 38 }); 39 } 40 41 42 public SelectEventDemo() { 43 setTitle("监听列表项选择事件"); 44 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 45 setBounds(100, 100, 400, 200); 46 contentPane = new JPanel(); 47 contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 48 contentPane.setLayout(new BorderLayout(0, 0)); 49 setContentPane(contentPane); 50 51 label = new JLabel(" "); 52 contentPane.add(label, BorderLayout.SOUTH); 53 54 JScrollPane scrollPane = new JScrollPane(); 55 contentPane.add(scrollPane, BorderLayout.CENTER); 56 57 list = new JList(); 58 list.addListSelectionListener(new ListSelectionListener() { 59 public void valueChanged(ListSelectionEvent e) { 60 do_list_valueChanged(e); 61 } 62 }); 63 scrollPane.setViewportView(list); 64 65 String[] listData = new String[7]; 66 listData[0] = "《诛仙》"; 67 listData[1] = "《流星幻剑》"; 68 listData[2] = "《终极插班生》"; 69 listData[3] = "《我的美女大小姐》"; 70 listData[4] = "《极品家丁》"; 71 listData[5] = "《跨过千年来爱你》"; 72 listData[6] = "《烈火如歌》"; 73 list.setListData(listData); 74 } 75 76 protected void do_list_valueChanged(ListSelectionEvent e) { 77 JOptionPane.showMessageDialog(this, "我喜欢的小说:" +list.getSelectedValue(), null, JOptionPane.INFORMATION_MESSAGE); 78 } 79 }
以上是关于监听JList列表项的单击事件的主要内容,如果未能解决你的问题,请参考以下文章
如何通过Powershell代码更改特定WPF列表框项的背景颜色?