import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class List implements ListSelectionListener
{
JList list;
public static void main(String [] args)
{
List gui=new List();
gui.go();
}
public void go()
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel();
frame.getContentPane().add(BorderLayout.CENTER,panel);
String [] listEntries ={"alpha","beta","gamma","delta","epslion","zeta","eta","theta"};
list=new JList(listEntries);
JScrollPane scroller=new JScrollPane(list);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
list.setVisibleRowCount(4);//设定显示的行数
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//限制用户只能选取一个项目
list.addListSelectionListener(this);
frame.setSize(300,300);
frame.setVisible(true);
}
public void valueChanged(ListSelectionEvent lse)
{
//如果没有加上这个if测试,你会得到两次的事件
if(!lse.getValueIsAdjusting())
{
String selection=(String)list.getSelectedValue();//这会返回一个Object,不一定是String
System.out.println(selection);
}
}
}
JList的使用实例
最新推荐文章于 2021-04-25 17:06:05 发布