當前位置:編程學習大全網 - 編程軟體 - java的JList監聽判斷怎麽寫?

java的JList監聽判斷怎麽寫?

主要的就是監聽要用ListSelectionListener,對整個jlist進行監聽即可,事件源e.getSource要強轉為JList,下面給出剛寫的例子:

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();

}

}

  • 上一篇:貓薄荷怎麽種?怎麽判斷種出來的是紫花貓薄荷還是大花貓薄荷
  • 下一篇:編程顯示編程字怎麽辦?
  • copyright 2024編程學習大全網