2
\$\begingroup\$

I was trying to learn to develop plug-ins in Eclipse and after following the tutorial provided with Eclipse, tried to expand the code by writing a short Java class to track and display mouse movements on a text area. I got the code for that too from an Oracle Java document. Following is the java class from where I call the mouse tracking class (MouseEventDemo):

package com.example.helloworld.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class SampleHandler extends AbstractHandler {
    /**
     * The constructor.
     */
    public SampleHandler() {
    }

    /**
     * the command has been executed, so extract the needed information
     * from the application context.
     */
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
        MouseEventDemo md = new MouseEventDemo();
        md.callStart();

        return null;
    }
}

Next, in the MouseEventDemo class, callStart() initiates GUI painting by calling createAndShowGUI() which in-turn calls MouseEventDemo class constructor and completes the job.

package com.example.helloworld.handlers;

import javax.swing.*;


import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class MouseEventDemo extends JPanel implements MouseListener {
    BlankArea blankArea;
    JTextArea textArea;
    static final String NEWLINE = System.getProperty("line.separator");
    String  wString;
    public void callStart(){
         try {
             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();
         }
         /* Turn off metal's use of bold fonts */
         UIManager.put("swing.boldMetal", Boolean.FALSE);
         createAndShowGUI();
         //Schedule a job for the event dispatch thread:
         //creating and showing this application's GUI.
         //creating threaded implementation
         /*javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                 createAndShowGUI();
             }
         });*/
    }

    public MouseEventDemo(String xx){
        super(new GridLayout(0,1));
        wString = xx;
        JOptionPane.showMessageDialog (null, "assigned");
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("MouseDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new MouseEventDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public MouseEventDemo(){
        JOptionPane.showMessageDialog (null, wString);
        blankArea = new BlankArea(Color.YELLOW);
        add(blankArea);
        textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setPreferredSize(new Dimension(200, 75));
        add(scrollPane);

        //Register for mouse events on blankArea and the panel.
        blankArea.addMouseListener(this);
        addMouseListener(this);
        setPreferredSize(new Dimension(450, 450));
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));    
    }


    void eventOutput(String eventDescription, MouseEvent e) {
        textArea.append(eventDescription + " detected on "
                + e.getComponent().getClass().getName()
                + "." + NEWLINE);
        textArea.setCaretPosition(textArea.getDocument().getLength());      
    }

    public void mousePressed(MouseEvent e) {
        eventOutput("Mouse pressed (# of clicks: "
                + e.getClickCount() + ")", e);
    }

    public void mouseReleased(MouseEvent e) {
        eventOutput("Mouse released (# of clicks: "
                + e.getClickCount() + ")", e);
    }

    public void mouseEntered(MouseEvent e) {
        eventOutput("Mouse entered", e);
    }

    public void mouseExited(MouseEvent e) {
        eventOutput("Mouse exited", e);
    }

    public void mouseClicked(MouseEvent e) {
        eventOutput("Mouse clicked (# of clicks: "
                + e.getClickCount() + ")", e);
    }
}

In all this, there are two object instances of MouseEventDemo getting created. First when callStart() is called from SampleHandler and then again in MouseEventDemo class within createAndShowGUI method. The first one is not used after the initial call at all and seems a complete waste and an inefficient use of resources (just to call one public method in MouseEventDemo).

Is there some better way of accomplishing the intended tasks?

\$\endgroup\$
1
\$\begingroup\$
  1. Try to divide Handler and Panel. For example, MouseEventDemoPanel will contain GUI construction and MouseEventDemoHandler will contain your mousePressed(), mouseMoved(), etc. And use the observer pattern.
  2. Try to move the callStart() method to the SampleHandler class. This allows you to call new MouseEventDemo() once.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.