我的代码存在一个小问题,我想要实现的目标:
JList
项时,它会弹出一个窗口,显示一条消息。到目前为止我写的代码:
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();
}
}
答案 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以防止输入错误。