Java mouse click and double-click control

xiaoxiao2021-03-06  108

Preface: In a project, in order to use convenience, we need to complete such a function, which is both a mouse click a Swing button, popup A dialog box, pop-up the B dialog box when you click the same button. The first implementation: First, I think of: mouseevent.getClickCount () == 1 or == 2 to distinguish, start thinking, only the test, only when the test is started, this will not have effects at all. When you click, everything is normal, and the a dialog is displayed. But when you double-click, the B dialog is displayed, and the A dialog is also pleasant, we have not invited him. :) It is also coming. In meditation: Take careful analysis, it is found that the A dialog box is not so selfless, it is indeed an invitation. When we double-click, there is a mouse event in the time series, and the backcount == 2 mouse event is only a clickcount == 2. In fact, whether you are a few times, Java always sends a mouse event once, from clickcount = 1, clickcount = 2, clickcount = 3 ... Send a solution to a resolution: Program receives a clickcount = 1 event, How do you know that it is the first event of the event, or click the event? If you click on the event, it will be handled; if you follow the event of a clickcount = 2, we will give up this event. In order to achieve such a difficult way, we have to wait for a while, wait for a while to see if there is a double-click event generation, if you have, give up the single click Event, if not, handle the incident. (Discovering a good!) Sample code: if (E.GetClickCount () == 1) {mousetimer = new javax.swing.timer (350, new actionListener () {public void actionPerformed (ActionEvent EVT) {system.out.println ("SINGLE"); mouseetimer.stop ();}}); mousetimer.Restart ();} else if (E.GETClickCount () == 2 && mouseetimer.srunning ()) {mouseetimer.stop (); system. Out.println ("double");} A suggestion: In fact, the solution given in the text is not perfect, and it can even be said to be stupid. But if you have to do this, there is no better way (personal opinion). Looking back, why do you encounter such a problem, the biggest reason is because you don't have click and double-click to respond to design, they can't be well compatible.

转载请注明原文地址:https://www.9cbs.com/read-96390.html

New Post(0)