如何在Java swing中使用鼠标?

时间:2018-11-21 00:40:29

标签: java swing programming-languages

该怎么做?

我要怎么做

public void mousePressed(MouseEvent e){
    switch(e.getActionCommand){

        case button1: System.out.println("button1 pressed"); 
                         break; 
        case button2: System.out.println("button2 pressed"); 
                         break;
        case button3: System.out.println("button3 pressed"); 
                        break; 
        case button4: System.out.println("button4 pressed"); 
                        break; 
        case button5: System.out.println("button5 pressed"); 
                        break;
    }
}

1 个答案:

答案 0 :(得分:0)

为回答您的问题,让我们从switch / case语句开始,它可以与Java中的数字和字符串一起使用。因此,当您在侦听器中捕获用户交互时,您需要处理String,解决方案是:您需要在Swing组件上使用方法setName(...),并在侦听器中捕获该名称,即String。看这个例子:

    public void mousePressed(MouseEvent e){
       Component c = (Component) e.getSource();
       switch(c.getName()){
         case "button1": System.out.println("button1 pressed"); 
            break; 
         case "button2": System.out.println("button2 pressed"); 
            break;
         case "button3": System.out.println("button3 pressed"); 
            break; 
         case "button4": System.out.println("button4 pressed"); 
            break; 
         case "button5": System.out.println("button5 pressed"); 
            break;
    }
}

但是,创建按钮时,请不要忘记为每个按钮使用setName(“ buttonX”)方法,因为在该方法中传递的名称必须与switch / case语句中的名称之一匹配。