怎样判断鼠标是否点在了jlist的选项上?
我想制做这么一个jlist:有三个选项 abc;当我点在这三个选项的上的时候,呈现选中状态;当我点在jlist空白处(没有选项的地方),取消选中状态。现在的问题是,我用e.getpoint()返回鼠标点击的坐标,用什么方法判断这个坐标是不是在空白处呢?
[解决办法]
这是实现楼主所想要效果的一个例子,点击查看可以看到是否选择了JList的某一项,取消选择会有提示
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");
}
}