2011-06-09 14 views

Respuesta

9

Intente utilizar MouseListener con interfaz

 public void mousePressed(MouseEvent e) { 
     if(e.getClickCount() >= 2){ 
      //do something 
     } 
    } 
4

Uso MouseListener

public class MouseEventDemo ... implements MouseListener 

e implementar

public void mouseClicked(MouseEvent e) { } 

Puede averiguar el valor clic desde int getClickCount() devuelve el número de rápida , clics consecutivos que ha realizado el usuario (incluido este evento). Por ejemplo, devuelve 2 para un doble clic.

2

u si están planeando escribir ur propia función para esto que se vaya algo de la siguiente manera:

captura el evento de ratón se hace clic, mantener un "timeStamp larga" inicializar a 0L como una variable de instancia,

ahora doble clic es dos clics dentro de 3 segundos o 5 seg

so 
{ 
if (timeStamp == 0L) { 

timeStamp = System.getCurrentTime(); //please chk the exact syntax of this... it gives  milli seconds 

} else if ((timeStamp + 5000) <= System.getCurrentTime()) // here i am giving time  window of 5 sec = 5000 milli seconds 

{ 
//do ur double click code; 
then set timeStamp back to 0; 
timeStamp = 0L; 

} else { 
//its first click 
timeStamp = System.getCurrentTime(); 

} 
} 
7

hmmm, básicamente todos los mensajes de ... son correctas, pero para la salida a la corect DoubleMouseClick se deben envolver a la javax.swing.Timer

por ejemplo

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class ClickListener extends MouseAdapter implements ActionListener { 

    private final static int clickInterval = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); 
    private MouseEvent lastEvent; 
    private Timer timer; 

    public ClickListener() { 
     this(clickInterval); 
    } 

    public ClickListener(int delay) { 
     timer = new Timer(delay, this); 
    } 

    @Override 
    public void mouseClicked(MouseEvent e) { 
     /*if (e.getClickCount() > 2) { 
      return; 
     } 
     lastEvent = e; 
     if (timer.isRunning()) { 
      timer.stop(); 
      doubleClick(lastEvent); 
     } else { 
      timer.restart(); 
     }*/ 

     if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) { 
      System.out.println("double"); 
      timer.stop(); 
     } else { 
      timer.restart(); 
     } 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     timer.stop(); 
     singleClick(lastEvent); 
    } 

    public void singleClick(MouseEvent e) { 
    } 

    public void doubleClick(MouseEvent e) { 
    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame("Double Click Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.addMouseListener(new ClickListener() { 

      @Override 
      public void singleClick(MouseEvent e) { 
       System.out.println("single"); 
      } 

      @Override 
      public void doubleClick(MouseEvent e) { 
       System.out.println("double"); 
      } 
     }); 
     frame.setPreferredSize(new Dimension(200, 200)); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

pero corerrect para SystemTray con TrayIcon se añada ActionListener

por ejemplo

import java.awt.*; 
import java.awt.event.*; 
import java.net.URL; 
import javax.swing.*; 

public class TrayIconDemo { 

    public static void main(String[] args) { 
     try {// Use an appropriate Look and Feel 
      //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); 
     } catch (UnsupportedLookAndFeelException ex) { 
      ex.printStackTrace(); 
     } catch (IllegalAccessException ex) { 
      ex.printStackTrace(); 
     } catch (InstantiationException ex) { 
      ex.printStackTrace(); 
     } catch (ClassNotFoundException ex) { 
      ex.printStackTrace(); 
     } 
     UIManager.put("swing.boldMetal", Boolean.FALSE);// Turn off metal's use of bold fonts  
     SwingUtilities.invokeLater(new Runnable() {//Schedule a job for the event-dispatching thread: adding TrayIcon. 

      @Override 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 

    private static void createAndShowGUI() { 
     if (!SystemTray.isSupported()) {//Check the SystemTray support 
      System.out.println("SystemTray is not supported"); 
      return; 
     } 
     final PopupMenu popup = new PopupMenu(); 
     final TrayIcon trayIcon = new TrayIcon(createImage("Icon/failed.png", "tray icon")); 
     final SystemTray tray = SystemTray.getSystemTray(); 
     MenuItem aboutItem = new MenuItem("About"); // Create a popup menu components 
     CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size"); 
     CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip"); 
     Menu displayMenu = new Menu("Display"); 
     MenuItem errorItem = new MenuItem("Error"); 
     MenuItem warningItem = new MenuItem("Warning"); 
     MenuItem infoItem = new MenuItem("Info"); 
     MenuItem noneItem = new MenuItem("None"); 
     MenuItem exitItem = new MenuItem("Exit"); 
     popup.add(aboutItem); //Add components to popup menu 
     popup.addSeparator(); 
     popup.add(cb1); 
     popup.add(cb2); 
     popup.addSeparator(); 
     popup.add(displayMenu); 
     displayMenu.add(errorItem); 
     displayMenu.add(warningItem); 
     displayMenu.add(infoItem); 
     displayMenu.add(noneItem); 
     popup.add(exitItem); 
     trayIcon.setPopupMenu(popup); 
     try { 
      tray.add(trayIcon); 
     } catch (AWTException e) { 
      System.out.println("TrayIcon could not be added."); 
      return; 
     } 
     trayIcon.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray"); 
      } 
     }); 
     aboutItem.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JOptionPane.showMessageDialog(null, "This dialog box is run from the About menu item"); 
      } 
     }); 
     cb1.addItemListener(new ItemListener() { 

      @Override 
      public void itemStateChanged(ItemEvent e) { 
       int cb1Id = e.getStateChange(); 
       if (cb1Id == ItemEvent.SELECTED) { 
        trayIcon.setImageAutoSize(true); 
       } else { 
        trayIcon.setImageAutoSize(false); 
       } 
      } 
     }); 
     cb2.addItemListener(new ItemListener() { 

      @Override 
      public void itemStateChanged(ItemEvent e) { 
       int cb2Id = e.getStateChange(); 
       if (cb2Id == ItemEvent.SELECTED) { 
        trayIcon.setToolTip("Sun TrayIcon"); 
       } else { 
        trayIcon.setToolTip(null); 
       } 
      } 
     }); 
     ActionListener listener = new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       MenuItem item = (MenuItem) e.getSource(); 
       System.out.println(item.getLabel()); //TrayIcon.MessageType type = null; 
       if ("Error".equals(item.getLabel())) {//type = TrayIcon.MessageType.ERROR ;     
        trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message", TrayIcon.MessageType.ERROR); 
       } else if ("Warning".equals(item.getLabel())) {//type = TrayIcon.MessageType.WARNING;      
        trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message", TrayIcon.MessageType.WARNING); 
       } else if ("Info".equals(item.getLabel())) { //type = TrayIcon.MessageType.INFO;     
        trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message", TrayIcon.MessageType.INFO); 
       } else if ("None".equals(item.getLabel())) {//type = TrayIcon.MessageType.NONE;      
        trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message", TrayIcon.MessageType.NONE); 
       } 
      } 
     }; 
     errorItem.addActionListener(listener); 
     warningItem.addActionListener(listener); 
     infoItem.addActionListener(listener); 
     noneItem.addActionListener(listener); 
     exitItem.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       tray.remove(trayIcon); 
       System.exit(0); 
      } 
     }); 
    } 

    protected static Image createImage(String path, String description) {//Obtain the image URL 
     URL imageURL = TrayIconDemo.class.getResource(path); 
     if (imageURL == null) { 
      System.err.println("Resource not found: " + path); 
      return null; 
     } else { 
      return (new ImageIcon(imageURL, description)).getImage(); 
     } 
    } 

    private TrayIconDemo() { 
    } 
} 
3
ActionListener actionListener = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     //Double click code here 
    } 
}; 

SystemTray tray = SystemTray.getSystemTray(); 
TrayIcon trayIcon = new TrayIcon(<icon stuff>); 

trayIcon.addActionListener(actionListener); 
tray.add(trayIcon); 

Esta es la forma en que trabajó para mí

1
trayIcon.addMouseListener(new java.awt.event.MouseAdapter() { 

    @Override 
    public void mouseClicked(java.awt.event.MouseEvent evt) { 
     if (evt.getClickCount() == 2) { 
      setVisible(true); 
      setExtendedState(JFrame.NORMAL); 
     } 
    } 

}); 
tray.add(trayIcon); 

Esto hará el trabajo.

Cuestiones relacionadas