public class BaiDuKnows extends JFrame implements ListSelectionListener
{
//创建列表
private JList jl=new JList()
private JLabel label =new JLabel("香蕉苹果大鸭梨等待你的选择!")
//创建字符串数组
private String[] str={"香蕉","苹果","大鸭梨"}
//创建复选框数组
public BaiDuKnows()
{
//设置列表的数据模型
jl.setListData(str)
//为列表注册ListSelectionEvent监听器
jl.addListSelectionListener(this)
jl.setBounds(0, 0, 150, 200)
label.setBounds(180, 0, 200, 200)
this.add(jl)
this.add(label)
this.setLayout(null)
this.setBounds(100,100,360,250)
this.setVisible(true)
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
//实现ListSelectionListener接口中的事件处理方法
public void valueChanged(ListSelectionEvent e)
{
Object obj=((JList)e.getSource()).getSelectedValue()
if(obj.equals("香蕉"))
{
label.setText("你选的是banana")
}
else if(obj.equals("苹果"))
{
label.setText("你选的是apple")
}
else if(obj.equals("大鸭梨"))
{
label.setText("你选的是pear")
}
else
{
label.setText("你选的是球!!")
}
}
public static void main(String[] args)
{
new BaiDuKnows()
}
}
因为鼠标按下的时候会触发事件,鼠标放开的时候又会触发一次事件。你可以判断event.getValueIsAdjusting(),只有第一次鼠标按下的时候才会返回true
ListSelectionListener listSelectionListener = new ListSelectionListener() {public void valueChanged(ListSelectionEvent listSelectionEvent) {
System.out.print("First index: " + listSelectionEvent.getFirstIndex())
System.out.print(", Last index: " + listSelectionEvent.getLastIndex())
boolean adjust = listSelectionEvent.getValueIsAdjusting()
System.out.println(", Adjusting? " + adjust)
if (!adjust) {
JList list = (JList) listSelectionEvent.getSource()
int selections[] = list.getSelectedIndices()
Object selectionValues[] = list.getSelectedValues()
for (int i = 0, n = selections.lengthi <ni++) {
if (i == 0) {
System.out.print(" Selections: ")
}
System.out.print(selections[i] + "/" + selectionValues[i] + " ")
}
System.out.println()
}
}
}
kcLst.addListSelectionListener(listSelectionListener)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)