Example usage for javax.swing JComponent addMouseListener

List of usage examples for javax.swing JComponent addMouseListener

Introduction

In this page you can find the example usage for javax.swing JComponent addMouseListener.

Prototype

public synchronized void addMouseListener(MouseListener l) 

Source Link

Document

Adds the specified mouse listener to receive mouse events from this component.

Usage

From source file:com.haulmont.cuba.desktop.sys.DesktopToolTipManager.java

protected void showTooltip(JComponent field, String text) {
    if (!field.isShowing())
        return;//  w  w w .ja  v  a 2s.  c  o m

    if (StringUtils.isEmpty(text)) {
        return;
    }

    PointerInfo pointerInfo = MouseInfo.getPointerInfo();
    if (pointerInfo == null) {
        return;
    }

    if (toolTipWindow != null) {
        hideTooltip();
    }

    component = field;

    final JToolTip toolTip = new CubaToolTip();
    toolTip.setTipText(text);

    // Location to display tooltip
    Point location = getToolTipLocation(pointerInfo, toolTip.getTipText());

    final Popup tooltipContainer = PopupFactory.getSharedInstance().getPopup(field, toolTip, location.x,
            location.y);
    tooltipContainer.show();

    window = tooltipContainer;
    toolTipWindow = toolTip;

    tooltipShowing = true;
    if (!(field instanceof ToolTipButton)) {
        toolTip.addMouseListener(this);
        field.addMouseListener(this);
    }
}

From source file:jatoo.app.App.java

public App(final String title) {

    this.title = title;

    ///*from  ww w . j  a v a  2s.  c o m*/
    // load properties

    properties = new AppProperties(new File(getWorkingDirectory(), "app.properties"));
    properties.loadSilently();

    //
    // resources

    texts = new ResourcesTexts(getClass(), new ResourcesTexts(App.class));
    images = new ResourcesImages(getClass(), new ResourcesImages(App.class));

    //
    // create & initialize the window

    if (isDialog()) {

        window = new JDialog((Frame) null, getTitle());

        if (isUndecorated()) {
            ((JDialog) window).setUndecorated(true);
            ((JDialog) window).setBackground(new Color(0, 0, 0, 0));
        }

        ((JDialog) window).setResizable(isResizable());
    }

    else {

        window = new JFrame(getTitle());

        if (isUndecorated()) {
            ((JFrame) window).setUndecorated(true);
            ((JFrame) window).setBackground(new Color(0, 0, 0, 0));
        }

        ((JFrame) window).setResizable(isResizable());
    }

    window.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(final WindowEvent e) {
            System.exit(0);
        }

        @Override
        public void windowIconified(final WindowEvent e) {
            if (isHideWhenMinimized()) {
                hide();
            }
        }
    });

    //
    // set icon images
    // is either all icons from initializer package
    // or all icons from app package

    List<Image> windowIconImages = new ArrayList<>();
    String[] windowIconImagesNames = new String[] { "016", "020", "022", "024", "032", "048", "064", "128",
            "256", "512" };

    for (String size : windowIconImagesNames) {
        try {
            windowIconImages.add(new ImageIcon(getClass().getResource("app-icon-" + size + ".png")).getImage());
        } catch (Exception e) {
        }
    }

    if (windowIconImages.size() == 0) {

        for (String size : windowIconImagesNames) {
            try {
                windowIconImages
                        .add(new ImageIcon(App.class.getResource("app-icon-" + size + ".png")).getImage());
            } catch (Exception e) {
            }
        }
    }

    window.setIconImages(windowIconImages);

    //
    // this is the place for to call init method
    // after all local components are created
    // from now (after init) is only configuration

    init();

    //
    // set content pane ( and ansure transparency )

    JComponent contentPane = getContentPane();
    contentPane.setOpaque(false);

    ((RootPaneContainer) window).setContentPane(contentPane);

    //
    // pack the window right after the set of the content pane

    window.pack();

    //
    // center window (as default in case restore fails)
    // and try to restore the last location

    window.setLocationRelativeTo(null);
    window.setLocation(properties.getLocation(window.getLocation()));

    if (!isUndecorated()) {

        if (properties.getLastUndecorated(isUndecorated()) == isUndecorated()) {

            if (isResizable() && isSizePersistent()) {

                final String currentLookAndFeel = String.valueOf(UIManager.getLookAndFeel());

                if (properties.getLastLookAndFeel(currentLookAndFeel).equals(currentLookAndFeel)) {
                    window.setSize(properties.getSize(window.getSize()));
                }
            }
        }
    }

    //
    // fix location if out of screen

    Rectangle intersection = window.getGraphicsConfiguration().getBounds().intersection(window.getBounds());

    if ((intersection.width < window.getWidth() * 1 / 2)
            || (intersection.height < window.getHeight() * 1 / 2)) {
        UIUtils.setWindowLocationRelativeToScreen(window);
    }

    //
    // restore some properties

    setAlwaysOnTop(properties.isAlwaysOnTop());
    setHideWhenMinimized(properties.isHideWhenMinimized());
    setTransparency(properties.getTransparency(transparency));

    //
    // null is also a good value for margins glue gaps (is [0,0,0,0])

    Insets marginsGlueGaps = getMarginsGlueGaps();
    if (marginsGlueGaps == null) {
        marginsGlueGaps = new Insets(0, 0, 0, 0);
    }

    //
    // glue to margins on Ctrl + ARROWS

    if (isGlueToMarginsOnCtrlArrows()) {

        UIUtils.setActionForCtrlDownKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginBottom(window, marginsGlueGaps.bottom));
        UIUtils.setActionForCtrlLeftKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginLeft(window, marginsGlueGaps.left));
        UIUtils.setActionForCtrlRightKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginRight(window, marginsGlueGaps.right));
        UIUtils.setActionForCtrlUpKeyStroke(((RootPaneContainer) window).getRootPane(),
                new ActionGlueMarginTop(window, marginsGlueGaps.top));
    }

    //
    // drag to move ( when provided component is not null )

    JComponent dragToMoveComponent = getDragToMoveComponent();

    if (dragToMoveComponent != null) {

        //
        // move the window by dragging the UI component

        int marginsGlueRange = Math.min(window.getGraphicsConfiguration().getBounds().width,
                window.getGraphicsConfiguration().getBounds().height);
        marginsGlueRange /= 60;
        marginsGlueRange = Math.max(marginsGlueRange, 15);

        UIUtils.forwardDragAsMove(dragToMoveComponent, window, marginsGlueRange, marginsGlueGaps);

        //
        // window popup

        dragToMoveComponent.addMouseListener(new MouseAdapter() {
            public void mouseReleased(final MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    windowPopup = getWindowPopup(e.getLocationOnScreen());
                    windowPopup.setVisible(true);
                }
            }
        });

        //
        // always dispose the popup when window lose the focus

        window.addFocusListener(new FocusAdapter() {
            public void focusLost(final FocusEvent e) {
                if (windowPopup != null) {
                    windowPopup.setVisible(false);
                    windowPopup = null;
                }
            }
        });
    }

    //
    // tray icon

    if (hasTrayIcon()) {

        if (SystemTray.isSupported()) {

            Image trayIconImage = windowIconImages.get(0);
            Dimension trayIconSize = SystemTray.getSystemTray().getTrayIconSize();

            for (Image windowIconImage : windowIconImages) {

                if (Math.abs(trayIconSize.width - windowIconImage.getWidth(null)) < Math
                        .abs(trayIconImage.getWidth(null) - windowIconImage.getWidth(null))) {
                    trayIconImage = windowIconImage;
                }
            }

            final TrayIcon trayIcon = new TrayIcon(trayIconImage);
            trayIcon.setPopupMenu(getTrayIconPopup());

            trayIcon.addMouseListener(new MouseAdapter() {
                public void mouseClicked(final MouseEvent e) {

                    if (SwingUtilities.isLeftMouseButton(e)) {
                        if (e.getClickCount() >= 2) {
                            if (window.isVisible()) {
                                hide();
                            } else {
                                show();
                            }
                        }
                    }
                }
            });

            try {
                SystemTray.getSystemTray().add(trayIcon);
            } catch (AWTException e) {
                logger.error(
                        "unexpected exception trying to add the tray icon ( the desktop system tray is missing? )",
                        e);
            }
        }

        else {
            logger.error("the system tray is not supported on the current platform");
        }
    }

    //
    // hidden or not

    if (properties.isVisible()) {
        window.setVisible(true);
    }

    //
    // close the splash screen
    // if there is one

    try {

        SplashScreen splash = SplashScreen.getSplashScreen();

        if (splash != null) {
            splash.close();
        }
    }

    catch (UnsupportedOperationException e) {
        getLogger().info("splash screen not supported", e);
    }

    //
    // add shutdown hook for #destroy()

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            App.this.destroy();
        }
    });

    //
    // after init

    afterInit();
}

From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java

protected void initTabContextMenu(JComponent tabComponent) {
    tabComponent.addMouseListener(new MouseAdapter() {
        @Override//from  w w w .ja  va  2s  .co  m
        public void mousePressed(MouseEvent e) {
            dispatchToParent(e);
            if (e.isPopupTrigger()) {
                showTabPopup(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            dispatchToParent(e);
            if (e.isPopupTrigger()) {
                showTabPopup(e);
            }
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            dispatchToParent(e);
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            dispatchToParent(e);
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            dispatchToParent(e);
        }

        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            dispatchToParent(e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            dispatchToParent(e);
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            dispatchToParent(e);
        }

        public void dispatchToParent(MouseEvent e) {
            tabsPane.dispatchEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, tabsPane));
        }
    });
}

From source file:com.pironet.tda.TDA.java

/**
 * display selected category in upper right frame
 *///from   w  ww. ja  v  a  2 s  .com
private void displayCategory(Object nodeInfo) {
    final Category cat = ((Category) nodeInfo);
    topSplitPane.getLeftComponent().setPreferredSize(topSplitPane.getLeftComponent().getSize());
    boolean needDividerPos = false;
    Dimension size = null;
    if (topSplitPane.getRightComponent() != null) {
        size = topSplitPane.getRightComponent().getSize();
    } else {
        needDividerPos = true;
    }
    setThreadDisplay(true);
    final JScrollPane lastView = cat.getLastView();
    if (lastView == null) {
        JComponent catComp = cat.getCatComponent(this);
        if (cat.getName().startsWith("Monitors") || cat.getName().startsWith("Threads blocked by Monitors")) {
            catComp.addMouseListener(getMonitorsPopupMenu());
        } else {
            catComp.addMouseListener(getCatPopupMenu());
        }
        final ViewScrollPane dumpView = new ViewScrollPane(catComp, runningAsVisualVMPlugin);
        if (size != null) {
            dumpView.setPreferredSize(size);
        }

        topSplitPane.setRightComponent(dumpView);
        cat.setLastView(dumpView);
    } else {
        if (size != null) {
            lastView.setPreferredSize(size);
        } else {
            lastView.setMinimumSize(Const.EMPTY_DIMENSION);
            lastView.setPreferredSize(Const.EMPTY_DIMENSION);
        }
        topSplitPane.setRightComponent(lastView);

    }

    if (cat.getCurrentlySelectedUserObject() != null) {
        displayThreadInfo(cat.getCurrentlySelectedUserObject());
    } else {
        displayContent(null);
    }
    if (needDividerPos) {
        topSplitPane.setDividerLocation(PrefManager.get().getTopDividerPos());
    }
    if (cat.howManyFiltered() > 0) {
        statusBar.setInfoText("Filtered " + cat.howManyFiltered()
                + " elements in this category. Showing remaining " + cat.showing() + " elements.");
    } else {
        statusBar.setInfoText(AppInfo.getStatusBarInfo());
    }

    displayContent(cat.getInfo());
}

From source file:org.bitbucket.mlopatkin.android.logviewer.widgets.UiHelper.java

public static void addPopupMenu(final JComponent component, final JPopupMenu menu) {
    component.addMouseListener(new MouseAdapter() {
        @Override/*from   w ww .j a v a2s. c o m*/
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showMenu(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                showMenu(e);
            }
        }

        private void showMenu(MouseEvent e) {
            menu.show(e.getComponent(), e.getX(), e.getY());
        }
    });
}

From source file:org.bitbucket.mlopatkin.android.logviewer.widgets.UiHelper.java

public static void addDoubleClickListener(JComponent component, final DoubleClickListener listener) {
    assert listener != null;
    component.addMouseListener(new MouseAdapter() {
        @Override//ww w . ja  v a2s .c  o m
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == DOUBLE_CLICK_COUNT && e.getButton() == MouseEvent.BUTTON1) {
                listener.mouseClicked(e);
            }
        }
    });
}

From source file:org.bitbucket.mlopatkin.android.logviewer.widgets.UiHelper.java

public static void addDoubleClickAction(JComponent component, final Action action) {
    component.addMouseListener(new MouseAdapter() {
        @Override//  w ww. j  a  va 2s .co m
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == DOUBLE_CLICK_COUNT && e.getButton() == MouseEvent.BUTTON1) {
                action.actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED,
                        (String) action.getValue(Action.ACTION_COMMAND_KEY), e.getWhen(), e.getModifiers()));
            }
        }
    });
}

From source file:org.datacleaner.widgets.table.DCTableCellRenderer.java

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    logger.debug("getTableCellRendererComponent({},{})", row, column);

    if (value != null) {
        if (value.getClass().isArray()) {
            // arrays are printed nicely this way
            value = ArrayUtils.toString(value);
        }//from w  ww. j  a v  a 2s .c  om
    }

    // icons are displayed as labels
    if (value instanceof Icon) {
        final JLabel label = new JLabel((Icon) value);
        label.setOpaque(true);
        value = label;
    }

    final Component result;

    // render components directly
    if (value instanceof JComponent) {
        final JComponent component = (JComponent) value;

        component.setOpaque(true);

        if (component.getMouseListeners().length == 0) {
            component.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    MouseEvent newEvent = SwingUtilities.convertMouseEvent(component, e, _table);
                    _table.consumeMouseClick(newEvent);
                }
            });
        }

        result = component;
    } else {
        result = _delegate.getTableCellRendererComponent(_table, value, isSelected, hasFocus, row, column);
        assert result instanceof JLabel;
    }

    // alignment is applied to all labels or panels (with flowlayout)
    Alignment alignment = _alignmentOverrides.get(column);
    if (alignment == null) {
        alignment = Alignment.LEFT;
    }

    // set alignment
    if (value instanceof JPanel) {
        final LayoutManager layout = ((JPanel) value).getLayout();
        if (layout instanceof FlowLayout) {
            final FlowLayout flowLayout = (FlowLayout) layout;
            flowLayout.setAlignment(alignment.getFlowLayoutAlignment());
        }
    } else if (result instanceof JLabel) {
        final JLabel label = (JLabel) result;
        label.setHorizontalAlignment(alignment.getSwingContstantsAlignment());

        WidgetUtils.setAppropriateFont(label);
    }

    return result;
}

From source file:org.nuclos.client.ui.collect.SubForm.java

private void addToolbarMouseListener(JComponent src, JComponent parent, JTable table) {
    final MouseListener ml = newToolbarContextMenuListener(parent, table);
    src.addMouseListener(ml);
    myMouseListener.add(new Pair<JComponent, MouseListener>(src, ml));
}

From source file:test.uk.co.modularaudio.util.swing.rollpainter.RPGestureRecogniser.java

public RPGestureRecogniser(JComponent componentToWatch) {
    this.componentToWatch = componentToWatch;

    componentToWatch.addMouseListener(this);
}