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