弹出窗口在JList元素-Java上按下时

时间:2015-02-15 17:52:19

标签: java swing list popup mouseevent

我的代码存在一个小问题,我想要实现的目标:

  1. 当我点击JList项时,它会弹出一个窗口,显示一条消息。
  2. 弹出窗口应该特别指我点击的那个元素,例如我按下车,它应该是"你点击的车是一辆车"
  3. 到目前为止我写的代码:

      import java.awt.FlowLayout;
      import java.awt.event.MouseAdapter;
      import java.awt.event.MouseEvent;
      import java.awt.event.MouseListener;
    
     import javax.swing.JFrame;
      javax.swing.JList;
     import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
      import javax.swing.ListSelectionModel;
    
          public class Test extends JFrame {
    private JList list;
    private static String[] names = { "car ", "bike", "skate" };
    
    public Test() {
        super("title");
        setLayout(new FlowLayout());
        setSize(650, 800);
    
        list = new JList(names);
        list.setVisibleRowCount(3);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(new JScrollPane(list));
        setVisible(true);
        MouseListener mouseListener = new MouseAdapter() {
            public void mouseisClicked(MouseEvent mouseEvent) {
                if (mouseEvent.getClickCount() == 2) {
                    JOptionPane.showMessageDialog(null, "testing");
                }
            }
        };
        setVisible(true);
    }
    
    public static void main(String agrs[]) {
        Test t1 = new Test();
    }
    }
    

1 个答案:

答案 0 :(得分:1)

您可以使用MouseEvent获取生成事件的组件:

JList list = (JList)mouseEvent.getSource();
System.out.println(list.getSelectedValue().toString());

编辑:

public void mouseisClicked(MouseEvent mouseEvent) {

您没有实施正确的方法。它应该是:

@Override
public void mouseClicked(MouseEvent mouseEvent) {

覆盖方法时始终使用@Override以防止输入错误。