Example usage for javax.swing SwingUtilities isLeftMouseButton

List of usage examples for javax.swing SwingUtilities isLeftMouseButton

Introduction

In this page you can find the example usage for javax.swing SwingUtilities isLeftMouseButton.

Prototype

public static boolean isLeftMouseButton(MouseEvent anEvent) 

Source Link

Document

Returns true if the mouse event specifies the left mouse button.

Usage

From source file:ja.lingo.application.gui.main.settings.dictionaries.add.AddPanel.java

public void onReaderListClicked(MouseEvent e) {
    if (!SwingUtilities.isLeftMouseButton(e)) {
        return;/*from  www .ja v a  2  s.  c  o  m*/
    }

    if (e.getClickCount() != 2) {
        return;
    }

    fileChooser.askForFile(parentDialog);
}

From source file:net.sourceforge.happybank.main.BankMain.java

private void initComponents() {
    frame = new javax.swing.JFrame();
    menuBar = new javax.swing.JMenuBar();
    menuFile = new javax.swing.JMenu();
    menuItemExit = new javax.swing.JMenuItem();
    menuActions = new javax.swing.JMenu();
    menuItemView = new javax.swing.JMenuItem();
    separator2 = new javax.swing.JSeparator();
    menuHelp = new javax.swing.JMenu();
    separator4 = new javax.swing.JSeparator();
    menuItemAbout = new javax.swing.JMenuItem();
    accountEntries = new javax.swing.JTable();
    accountModel = new AccountTableModel();

    /*//from   w  w w  .j a  v  a 2s .  c  o  m
     * File menu
     */
    menuFile.setMnemonic('F');
    menuFile.setText("File");
    // - Exit option
    menuItemExit.setMnemonic('X');
    menuItemExit.setText("Exit");
    menuItemExit.setActionCommand("Exit");
    menuItemExit.addActionListener(new ActionHandler());
    menuFile.add(menuItemExit);
    menuBar.add(menuFile);

    // Actions menu
    menuActions.setMnemonic('A');
    menuActions.setText("Actions");
    // - View option
    menuItemView.setMnemonic('V');
    menuItemView
            .setAccelerator(KeyStroke.getKeyStroke('V', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    menuItemView.setText("View");
    menuItemView.setActionCommand("View");
    menuItemView.addActionListener(new ActionHandler());
    menuActions.add(menuItemView);
    menuActions.add(separator2);

    // Help menu
    menuHelp.setMnemonic('H');
    menuHelp.setText("Help");
    // - About option
    menuHelp.add(separator4);
    menuItemAbout.setMnemonic('A');
    menuItemAbout.setText("About");
    menuItemAbout.setActionCommand("About");
    menuItemAbout.addActionListener(new ActionHandler());
    menuHelp.add(menuItemAbout);
    menuBar.add(menuHelp);

    /*
     * configure the TabListCellRenderer
     */
    accountEntries.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    accountEntries.setAutoCreateColumnsFromModel(false);
    accountEntries.setModel(accountModel);
    accountEntries.getTableHeader().setReorderingAllowed(false);
    accountEntries.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    accountEntries.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            // capture single click
            if (evt.getClickCount() == 1 && SwingUtilities.isLeftMouseButton(evt)) {
                // ignore
            }
            // capture double click
            if (evt.getClickCount() == 2) {
                // edit the account
                int row = accountEntries.rowAtPoint(evt.getPoint());
                accountEntries.setRowSelectionInterval(row, row);
                onViewAccount();
            }
        } // mouseClicked
    }); // MouseAdapter

    // set the column widths and alignment
    for (int k = 0; k < AccountTableModel.COLUMNS.length; k++) {
        TableCellEditor zipper = new DefaultCellEditor(new JTextField());
        DefaultTableCellRenderer textRenderer = new DefaultTableCellRenderer();
        textRenderer.setHorizontalAlignment(AccountTableModel.COLUMNS[k].cAlignment);
        TableColumn column = new TableColumn(k, AccountTableModel.COLUMNS[k].cWidth, textRenderer, zipper);
        accountEntries.addColumn(column);
    }

    // set the table header
    JTableHeader header = accountEntries.getTableHeader();
    header.setUpdateTableInRealTime(false);

    /*
     * create the selection area
     */
    accountPanel = new JPanel();
    accountPanel.setLayout(new BorderLayout());
    scrollPane = new JScrollPane(accountEntries);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new java.awt.Dimension(750, 300));
    accountPanel.add(scrollPane);
    frame.getContentPane().add(accountPanel, java.awt.BorderLayout.CENTER);

    /*
     * layout the frame
     */
    frame.setJMenuBar(menuBar);
    frame.setTitle(APP_NAME);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(screenSize.width / 2 - 300, screenSize.height / 2 - 200);
    // add a listener for the close event
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            onExit();
        }
    });

    loadAccounts();
}

From source file:org.adempiere.apps.graph.PerformanceIndicator.java

/**
*    Init Graph Display//  w  w  w  . j a v a2 s  . co  m
*  Kinamo (pelgrim)
*/
private void init() {
    chartPanel = new ChartPanel(createChart(), //chart
            false, //boolean properties
            false, // boolean save
            false, //boolean print
            false, //boolean zoom
            true //boolean tooltips
    );
    chartPanel.setPreferredSize(indicatordimension);

    chartPanel.addChartMouseListener(new org.jfree.chart.ChartMouseListener() {
        public void chartMouseClicked(org.jfree.chart.ChartMouseEvent e) {
            //plot p = (MeterPlot) e.getSource();
            MouseEvent me = e.getTrigger();
            if (SwingUtilities.isLeftMouseButton(me) && me.getClickCount() > 1)
                fireActionPerformed(me);
            if (SwingUtilities.isRightMouseButton(me))
                popupMenu.show((Component) me.getSource(), me.getX(), me.getY());
        }

        public void chartMouseMoved(org.jfree.chart.ChartMouseEvent e) {

        }
    });

    this.add(chartPanel, BorderLayout.NORTH);
    this.setMinimumSize(paneldimension);
    this.setMaximumSize(paneldimension);
    //---------------------------------------------

    invalidate();
}

From source file:com.diversityarrays.kdxplore.curate.TraitsAndInstancesPanel2.java

public TraitsAndInstancesPanel2(CurationContext cc, Font smallFont, TIStatsTableModel tistm,
        boolean anyInstanceNumbers, int nInvalidRules, String tAndIpanelLabel,
        CurationMenuProvider curationMenuProvider, Consumer<List<OutlierSelection>> outlierConsumer) {
    super(new BorderLayout());

    this.curationContext = cc;
    this.outlierConsumer = outlierConsumer;
    this.curationMenuProvider = curationMenuProvider;

    this.tiStatsModel = tistm;

    curationContext.addPropertyChangeListener(propertyChangeListener);

    traitInstanceStatsTable = new TraitInstanceStatsTable(tiStatsModel);

    traitInstanceStatsTable.addPropertyChangeListener("rowSorter", rowSorterChangeListener);
    traitInstanceStatsTable.setAutoCreateRowSorter(true);

    traitInstanceStatsTable.addMouseListener(new MouseAdapter() {
        @Override/*from  w  w w .ja  va2 s  . c o  m*/
        public void mouseClicked(MouseEvent me) {
            int clickCount = me.getClickCount();

            if (SwingUtilities.isRightMouseButton(me) && 1 == clickCount) {
                me.consume();
                showContextMenu(me);
            } else if (SwingUtilities.isLeftMouseButton(me) && 2 == clickCount) {
                showTraitInstanceInfo(me);
            }
        }
    });

    Map<String, TableColumn[]> tableColumnsByChoice = createInstanceTableColumnsByChoice();
    TableColumnSelectionButton tcsb = new TableColumnSelectionButton(traitInstanceStatsTable,
            tableColumnsByChoice);

    StringCellRenderer scRenderer = new StringCellRenderer();
    scRenderer.setHorizontalAlignment(SwingConstants.CENTER);

    statDetailRenderer.setHorizontalAlignment(SwingConstants.CENTER);

    traitInstanceStatsTable.setDefaultRenderer(String.class, scRenderer);
    Transformer<TraitInstance, String> instanceNameTransformer = new Transformer<TraitInstance, String>() {
        @Override
        public String transform(TraitInstance ti) {
            return curationContext.makeTraitInstanceName(ti);
        }
    };
    TraitInstanceCellRenderer tiRenderer = new TraitInstanceCellRenderer(
            curationContext.getTraitColorProvider(), instanceNameTransformer);
    tiRenderer.setName("FOR-STATS-TABLE"); //$NON-NLS-1$
    traitInstanceStatsTable.setDefaultRenderer(TraitInstance.class, tiRenderer);
    traitInstanceStatsTable.setDefaultRenderer(Comparable.class, statDetailRenderer);

    TableColumnModel tcm = traitInstanceStatsTable.getColumnModel();
    Integer viewColumnIndex = tistm.getViewColumnIndex();
    if (viewColumnIndex != null) {
        TableColumn viewColumn = tcm.getColumn(viewColumnIndex);
        viewColumn.setMaxWidth(40);
        viewColumn.setCellRenderer(new OptionalCheckboxRenderer("No Values"));
    }

    if (nInvalidRules <= 0) {
        // Hide that column!
        int columnIndex = tistm.getValRuleErrorColumnIndex();
        columnIndex = traitInstanceStatsTable.convertColumnIndexToView(columnIndex);
        if (columnIndex >= 0) {
            TableColumn c = tcm.getColumn(columnIndex);
            tcm.removeColumn(c);
        }
    }

    TableColumn dataTypeTableColumn = traitInstanceStatsTable.getColumnModel()
            .getColumn(tistm.getTraitInstanceDatatypeColumnIndex());
    dataTypeTableColumn.setCellRenderer(new TraitDataTypeRenderer());

    Function<JTable, JScrollPane> scrollMaker = new Function<JTable, JScrollPane>() {
        @Override
        public JScrollPane apply(JTable t) {
            return new PromptScrollPane(t, "Select Trait in the Panel: " + tAndIpanelLabel);
        }
    };
    TitledTablePanelWithResizeControls ttp = new TitledTablePanelWithResizeControls("Trait Instances",
            traitInstanceStatsTable, smallFont, scrollMaker);
    ttp.scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    ttp.scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, tcsb);

    new CurationContextOptionsPopup(curationContext, ttp.separator);

    if (anyInstanceNumbers) {
        tcsb.setSelectedColumns(SimpleStatistics.GROUP_BASIC_STATS);
    } else {
        Set<Object> headerValues = new HashSet<>();
        for (TableColumn tc : tableColumnsByChoice.get(SimpleStatistics.GROUP_BASIC_STATS)) {
            headerValues.add(tc.getHeaderValue());
        }
        headerValues.remove(tistm.getInstanceHeading());
        tcsb.initialiseSelectedColumns(new Predicate<Object>() {
            @Override
            public boolean evaluate(Object hvalue) {
                return headerValues.contains(hvalue);
            }
        });
    }

    add(ttp, BorderLayout.CENTER);
}

From source file:dbseer.gui.panel.DBSeerSelectableChartPanel.java

@Override
public void mouseClicked(MouseEvent event) {
    super.mouseClicked(event);

    if (SwingUtilities.isLeftMouseButton(event) && event.getClickCount() == 2) {
        final JFreeChart chartToExplain = getChart();
        if (chartToExplain.getPlot() instanceof PiePlot) {
            return;
        }//w ww  .j  a v  a 2 s.  c o m
        DBSeerXYLineAndShapeRenderer renderer = (DBSeerXYLineAndShapeRenderer) chartToExplain.getXYPlot()
                .getRenderer();
        renderer.setLastSeriesAndCategory(-1, -1);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    DBSeerPlotExplainFrame newFrame = new DBSeerPlotExplainFrame(
                            (JFreeChart) chartToExplain.clone());
                    //                  newFrame.setPreferredSize(new Dimension(1280,800));
                    newFrame.pack();
                    newFrame.setLocationRelativeTo(DBSeerGUI.mainFrame);
                    newFrame.setVisible(true);
                } catch (CloneNotSupportedException e) {
                    JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
}

From source file:dbseer.gui.panel.DBSeerSelectableChartPanel.java

@Override
public void chartMouseClicked(ChartMouseEvent chartMouseEvent) {
    ChartEntity entity = chartMouseEvent.getEntity();
    MouseEvent mouseEvent = chartMouseEvent.getTrigger();

    if (SwingUtilities.isLeftMouseButton(mouseEvent) && entity != null && entity instanceof PieSectionEntity) {
        java.util.List<String> names = dataset.getTransactionTypeNames();
        PieSectionEntity pieSectionEntity = (PieSectionEntity) entity;
        int idx = pieSectionEntity.getSectionIndex();

        String name = (String) JOptionPane.showInputDialog(null, "Enter the name for this transaction type",
                "Transaction Type", JOptionPane.PLAIN_MESSAGE, null, null, "");

        if (name != null) {
            if (names.contains(name) && !names.get(idx).equals(name) && !name.isEmpty()) {
                JOptionPane.showMessageDialog(null,
                        "Please enter a different name for the transaction type.\nEach name has to be unique.",
                        "Warning", JOptionPane.WARNING_MESSAGE);
            } else {
                PieDataset oldDataset = pieSectionEntity.getDataset();
                DefaultPieDataset newDataset = new DefaultPieDataset();

                PiePlot plot = (PiePlot) chart.getPlot();
                String oldName = (String) oldDataset.getKey(idx);
                names.set(idx, name);//from w ww  . j  a  v a  2  s. c o m
                dataset.setTransactionTypeName(idx, name);

                for (int i = 0; i < oldDataset.getItemCount(); ++i) {
                    String key = (String) oldDataset.getKey(i);
                    Number number = oldDataset.getValue(i);

                    if (key.equals(oldName)) {
                        if (name.isEmpty())
                            newDataset.setValue("Transaction Type " + (i + 1), number);
                        else
                            newDataset.setValue(name, number);
                    } else {
                        newDataset.setValue(key, number);
                    }
                }

                Paint[] tempPaint = new Paint[oldDataset.getItemCount()];
                for (int i = 0; i < oldDataset.getItemCount(); ++i) {
                    String key = (String) oldDataset.getKey(i);
                    tempPaint[i] = plot.getSectionPaint(key);
                }

                ((DefaultPieDataset) oldDataset).clear();
                plot.setDataset(newDataset);

                for (int i = 0; i < newDataset.getItemCount(); ++i) {
                    String key = (String) newDataset.getKey(i);
                    plot.setSectionPaint(key, tempPaint[i]);
                }
            }
        }
    }
}

From source file:org.adempiere.apps.graph.PerformanceIndicator.java

/**************************************************************************
 *    Mouse Clicked/*from w  w w  .  j ava  2  s .  com*/
 *   @param e mouse event
 */
public void mouseClicked(MouseEvent e) {
    if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() > 1)
        fireActionPerformed(e);
    if (SwingUtilities.isRightMouseButton(e))
        popupMenu.show((Component) e.getSource(), e.getX(), e.getY());
}

From source file:com.projity.pm.graphic.graph.GraphInteractor.java

public void mouseReleased(MouseEvent e) {
    if (isReadOnly())
        return;/*from   ww  w  . ja va  2 s . c  o m*/
    if (!SwingUtilities.isLeftMouseButton(e))
        return;
    if (selected == null || state == NOTHING_SELECTED)
        return;
    if (isRepaintOnRelease())
        getGraph().repaint();

    double x1 = e.getX();
    double y1 = e.getY();
    executeAction(x1, y1);
    reset();
    findState(x1, y1);
}

From source file:jatoo.app.App.java

public App(final String title) {

    this.title = title;

    ////from   w w  w.  ja  va 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:ec.util.chart.swing.Charts.java

public static boolean isPopup(@Nonnull MouseEvent e) {
    return !SwingUtilities.isLeftMouseButton(e);
}