日期:2014-05-20 浏览次数:20835 次
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
public class MyDemo1 extends JFrame implements MouseListener,ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==btn){
Object selectedObject=list.getSelectedValue();
if(selectedObject!=null){
JOptionPane.showMessageDialog(null,"选择项目"+selectedObject );
System.out.println("选择项目"+selectedObject);
}else{
JOptionPane.showMessageDialog(null,"没选择任何项目" );
System.out.println("没选择任何项目");
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("mouseClicked");
Point p=e.getPoint();
if(list.contains(p)){//判断是否在JList的区域范围内
System.out.println("合法范围");
}else{
System.out.println("无效范围");
list.clearSelection();//不在区域范围内取消选择
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("mousePressed");
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
private String[] names={"A","B","C"};
private JList list=null;
private JButton btn=null;
private Container container=null;
public MyDemo1(String title){
super(title);
btn=new JButton("查看");
list=new JList(names);
container=this.getContentPane();
container.setLayout(new BorderLayout());
container.add(list,BorderLayout.WEST);
container.add(btn,BorderLayout.EAST);
// list.
btn.addActionListener(this);
this.addMouseListener(this);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args){
new MyDemo1("demo");
}
}