Example usage for java.awt.event MouseAdapter MouseAdapter

List of usage examples for java.awt.event MouseAdapter MouseAdapter

Introduction

In this page you can find the example usage for java.awt.event MouseAdapter MouseAdapter.

Prototype

MouseAdapter

Source Link

Usage

From source file:com.openbravo.pos.sales.JTicketLines.java

/** Creates new form JLinesTicket */
public JTicketLines(AppView app, String propertyRowHeight, String propertyFontsize, String ticketline) {
    this.m_App = app;
    initComponents();/*from   w  w w .java 2 s  .  com*/

    m_jTicketTable.m_App = app;
    m_jTicketTable.propertyRowHeight = propertyRowHeight;

    ColumnTicket[] acolumns = new ColumnTicket[0];

    if (ticketline != null) {
        try {
            if (m_sp == null) {
                SAXParserFactory spf = SAXParserFactory.newInstance();
                m_sp = spf.newSAXParser();
            }
            ColumnsHandler columnshandler = new ColumnsHandler();
            m_sp.parse(new InputSource(new StringReader(ticketline)), columnshandler);
            acolumns = columnshandler.getColumns();

        } catch (ParserConfigurationException ePC) {
            logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
        } catch (SAXException eSAX) {
            logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
        } catch (IOException eIO) {
            logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
        }
    }

    Map<String, Integer> widths = PropertyUtil.getTicketLineWidths(m_App);
    for (ColumnTicket acolumn : acolumns) {
        Integer width = widths.get(acolumn.name);
        if (width == null) {
            continue;
        }
        acolumn.width = width;
    }

    m_jTableModel = new TicketTableModel(acolumns);
    m_jTicketTable.setModel(m_jTableModel);

    m_jTicketTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
    TableColumnModel jColumns = m_jTicketTable.getColumnModel();
    for (int i = 0; i < acolumns.length; i++) {
        jColumns.getColumn(i).setPreferredWidth(acolumns[i].width);
        jColumns.getColumn(i).setResizable(true);
    }

    PropertyUtil.ScaleScrollbar(m_App, m_jScrollTableTicket);

    m_jTicketTable.getTableHeader().setReorderingAllowed(false);
    // m_jTicketTable.setDefaultRenderer(Object.class, new
    // TicketCellRenderer(app, acolumns, propertyFontsize));
    m_jTicketTable.setDefaultRenderer(Object.class,
            new RowHeightCellRenderer(app, acolumns, propertyFontsize, propertyRowHeight));

    PropertyUtil.ScaleTableColumnFontsize(m_App, m_jTicketTable, "sales-tablecolumn-fontsize", "14");

    m_jTicketTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    m_jTicketTable.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            JTable table = (JTable) me.getSource();
            Point p = me.getPoint();
            int row = table.rowAtPoint(p);
            if (me.getClickCount() == 2) {
                // your valueChanged overridden method
                listDoubleClickListener.valueChanged(new ListSelectionEvent(m_jTicketTable, row, row, false));
            }
        }
    });
    // reseteo la tabla...
    m_jTableModel.clear();
}

From source file:de.codesourcery.eve.skills.ui.components.impl.planning.CalendarComponent.java

@Override
protected JPanel createPanel() {

    addEntryButton.setEnabled(false);//from w ww . j a  v a 2  s.c o  m
    addEntryButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            addNewCalendarEntry();
        }

    });

    calendarWidget.addSelectionListener(new ISelectionListener<Date>() {

        @Override
        public void selectionChanged(Date selected) {
            addEntryButton.setEnabled(selected != null);
            tableModel.refresh();
        }
    });

    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() != 2 || e.isPopupTrigger()) {
                return;
            }

            final int viewRow = table.rowAtPoint(e.getPoint());
            if (viewRow != -1) {
                editCalendarEntry(tableModel.getRow(table.convertRowIndexToModel(viewRow)));
            }
        }
    });

    table.setFillsViewportHeight(true);
    table.setRowSorter(tableModel.getRowSorter());
    table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    final PopupMenuBuilder menuBuilder = new PopupMenuBuilder();

    menuBuilder.addItem("Remove", new AbstractAction() {

        @Override
        public boolean isEnabled() {
            return !ArrayUtils.isEmpty(table.getSelectedRows());
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            final int[] viewRows = table.getSelectedRows();
            if (ArrayUtils.isEmpty(viewRows)) {
                return;
            }

            final int[] modelRows = new int[viewRows.length];
            int i = 0;
            for (int viewRow : viewRows) {
                modelRows[i++] = table.convertRowIndexToModel(viewRow);
            }

            final List<ICalendarEntry> removedEntries = new ArrayList<ICalendarEntry>();

            for (int modelRow : modelRows) {
                removedEntries.add(tableModel.getRow(modelRow));
            }

            for (ICalendarEntry toBeRemoved : removedEntries) {
                calendarManager.getCalendar().deleteEntry(toBeRemoved);
            }
        }
    });

    menuBuilder.addItem("Edit...", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final int modelRow = table.convertRowIndexToModel(table.getSelectedRows()[0]);
            editCalendarEntry(tableModel.getRow(modelRow));
        }

        @Override
        public boolean isEnabled() {
            return !ArrayUtils.isEmpty(table.getSelectedRows());
        }
    });

    menuBuilder.attach(table);

    // controls panel
    final JPanel controlsPanel = new JPanel();

    controlsPanel.setLayout(new GridBagLayout());
    controlsPanel.add(addEntryButton, constraints(0, 0).noResizing().end());

    // combine panels
    final JPanel subPanel = new JPanel();

    subPanel.setLayout(new GridBagLayout());

    subPanel.add(controlsPanel, constraints(0, 0).useRelativeWidth().weightY(0).end());
    subPanel.add(new JScrollPane(table), constraints(0, 1).useRelativeWidth().useRemainingHeight().end());

    final ImprovedSplitPane splitPane = new ImprovedSplitPane(JSplitPane.HORIZONTAL_SPLIT, calendarWidget,
            subPanel);

    splitPane.setDividerLocation(0.7);

    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());

    result.add(splitPane, constraints(0, 0).resizeBoth().end());

    return result;
}

From source file:com.raddle.tools.ClipboardTransferMain.java

public ClipboardTransferMain() {
    super();//from  w ww. j a  v  a 2 s .  c o m
    initGUI();
    //// ??
    Properties p = new Properties();
    File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties");
    if (pf.exists()) {
        try {
            p.load(new FileInputStream(pf));
            serverAddrTxt.setText(StringUtils.defaultString(p.getProperty("server.addr")));
            portTxt.setText(StringUtils.defaultString(p.getProperty("local.port")));
            modifyClipChk.setSelected("true".equals(p.getProperty("allow.modify.local.clip")));
            autoChk.setSelected("true".equals(p.getProperty("auto.modify.remote.clip")));
        } catch (Exception e) {
            updateMessage(e.getMessage());
        }
    }
    m.addListener(new ClipboardListener() {

        @Override
        public void contentChanged(Clipboard clipboard) {
            setRemoteClipboard(false);
        }
    });
    m.setEnabled(autoChk.isSelected());
    //
    try {
        pasteImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_paste.png"));
        grayImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_gray.png"));
        sendImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/mail-send.png"));
        BufferedImage taskImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/taskbar.png"));
        setIconImage(taskImage);
        SystemTray systemTray = SystemTray.getSystemTray();
        trayIcon = new TrayIcon(grayImage, "??");
        systemTray.add(trayIcon);
        ////
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {// ???
                    if (ClipboardTransferMain.this.isVisible()) {
                        ClipboardTransferMain.this.setState(ICONIFIED);
                    } else {
                        ClipboardTransferMain.this.setVisible(true);
                        ClipboardTransferMain.this.setState(NORMAL);
                    }
                }
            }
        });
        ////// event 
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowIconified(WindowEvent e) {
                ClipboardTransferMain.this.setVisible(false);
                super.windowIconified(e);
            }

            @Override
            public void windowClosing(WindowEvent e) {
                File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties");
                pf.getParentFile().mkdirs();
                try {
                    Properties op = new Properties();
                    op.setProperty("server.addr", serverAddrTxt.getText());
                    op.setProperty("local.port", portTxt.getText());
                    op.setProperty("allow.modify.local.clip", modifyClipChk.isSelected() + "");
                    op.setProperty("auto.modify.remote.clip", autoChk.isSelected() + "");
                    FileOutputStream os = new FileOutputStream(pf);
                    op.store(os, "clip-trans");
                    os.flush();
                    os.close();
                } catch (Exception e1) {
                }
                shutdown();
                super.windowClosing(e);
            }
        });
    } catch (Exception e) {
        updateMessage(e.getMessage());
    }
    Thread thread = new Thread() {

        @Override
        public void run() {
            while (true) {
                try {
                    String poll = iconQueue.take();
                    if ("send".equals(poll)) {
                        trayIcon.setImage(grayImage);
                    } else if ("paste".equals(poll)) {
                        Thread.sleep(20);
                        trayIcon.setImage(grayImage);
                    }
                } catch (InterruptedException e1) {
                    return;
                }
            }
        }
    };
    thread.setDaemon(true);
    thread.start();
}

From source file:gtu._work.ui.RegexDirReplacer.java

private void initGUI() {
    try {/*from  www .  ja  v  a2  s  . co  m*/
        {
        }
        BorderLayout thisLayout = new BorderLayout();
        getContentPane().setLayout(thisLayout);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("source", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        ListModel srcListModel = new DefaultListModel();
                        srcList = new JList();
                        jScrollPane1.setViewportView(srcList);
                        srcList.setModel(srcListModel);
                        {
                            panel = new JPanel();
                            jScrollPane1.setRowHeaderView(panel);
                            panel.setLayout(new FormLayout(
                                    new ColumnSpec[] { ColumnSpec.decode("default:grow"), },
                                    new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,
                                            FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
                                            FormFactory.DEFAULT_ROWSPEC, }));
                            {
                                childrenDirChkbox = new JCheckBox("??");
                                childrenDirChkbox.setSelected(true);
                                panel.add(childrenDirChkbox, "1, 1");
                            }
                            {
                                subFileNameText = new JTextField();
                                panel.add(subFileNameText, "1, 2, fill, default");
                                subFileNameText.setColumns(10);
                                subFileNameText.setText("(txt|java)");
                            }
                            {
                                replaceOldFileChkbox = new JCheckBox("");
                                replaceOldFileChkbox.setSelected(true);
                                panel.add(replaceOldFileChkbox, "1, 3");
                            }
                            {
                                charsetText = new JTextField();
                                panel.add(charsetText, "1, 5, fill, default");
                                charsetText.setColumns(10);
                                charsetText.setText("UTF8");
                            }
                        }
                        srcList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                JListUtil.newInstance(srcList).defaultMouseClickOpenFile(evt);

                                JPopupMenuUtil.newInstance(srcList).applyEvent(evt)//
                                        .addJMenuItem("load files from clipboard", new ActionListener() {
                                            public void actionPerformed(ActionEvent arg0) {
                                                String content = ClipboardUtil.getInstance().getContents();
                                                DefaultListModel model = (DefaultListModel) srcList.getModel();
                                                StringTokenizer tok = new StringTokenizer(content, "\t\n\r\f",
                                                        false);
                                                for (; tok.hasMoreElements();) {
                                                    String val = ((String) tok.nextElement()).trim();
                                                    model.addElement(new File(val));
                                                }
                                            }
                                        }).show();
                            }
                        });
                        srcList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                JListUtil.newInstance(srcList).defaultJListKeyPressed(evt);
                            }
                        });
                    }
                }
                {
                    addDirFiles = new JButton();
                    jPanel1.add(addDirFiles, BorderLayout.NORTH);
                    addDirFiles.setText("add dir files");
                    addDirFiles.addActionListener(new ActionListener() {

                        public void actionPerformed(ActionEvent evt) {
                            File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog()
                                    .getApproveSelectedFile();
                            if (file == null || !file.isDirectory()) {
                                return;
                            }

                            List<File> fileLst = new ArrayList<File>();

                            String subName = StringUtils.trimToEmpty(subFileNameText.getText());
                            if (StringUtils.isBlank(subName)) {
                                subName = ".*";
                            }
                            String patternStr = ".*\\." + subName;

                            if (childrenDirChkbox.isSelected()) {
                                FileUtil.searchFileMatchs(file, patternStr, fileLst);
                            } else {
                                for (File f : file.listFiles()) {
                                    if (f.isFile() && f.getName().matches(patternStr)) {
                                        fileLst.add(f);
                                    }
                                }
                            }

                            DefaultListModel model = new DefaultListModel();
                            for (File f : fileLst) {
                                model.addElement(f);
                            }
                            srcList.setModel(model);
                        }
                    });
                }
            }
            {
                jPanel2 = new JPanel();
                BorderLayout jPanel2Layout = new BorderLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("param", null, jPanel2, null);
                {
                    exeucte = new JButton();
                    jPanel2.add(exeucte, BorderLayout.SOUTH);
                    exeucte.setText("exeucte");
                    exeucte.setPreferredSize(new java.awt.Dimension(491, 125));
                    exeucte.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            exeucteActionPerformed(evt);
                        }
                    });
                }
                {
                    jPanel3 = new JPanel();
                    GroupLayout jPanel3Layout = new GroupLayout((JComponent) jPanel3);
                    jPanel3.setLayout(jPanel3Layout);
                    jPanel2.add(jPanel3, BorderLayout.CENTER);
                    {
                        repFromText = new JTextField();
                    }
                    {
                        repToText = new JTextField();
                    }
                    jPanel3Layout.setHorizontalGroup(jPanel3Layout.createSequentialGroup()
                            .addContainerGap(25, 25)
                            .addGroup(jPanel3Layout.createParallelGroup()
                                    .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repFromText,
                                            GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repToText,
                                            GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE)))
                            .addContainerGap(20, Short.MAX_VALUE));
                    jPanel3Layout.setVerticalGroup(jPanel3Layout.createSequentialGroup().addContainerGap()
                            .addComponent(repFromText, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(repToText, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
                }
                {
                    addToTemplate = new JButton();
                    jPanel2.add(addToTemplate, BorderLayout.NORTH);
                    addToTemplate.setText("add to template");
                    addToTemplate.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            prop.put(repFromText.getText(), repToText.getText());
                            reloadTemplateList();
                        }
                    });
                }
            }
            {
                jPanel4 = new JPanel();
                BorderLayout jPanel4Layout = new BorderLayout();
                jPanel4.setLayout(jPanel4Layout);
                jTabbedPane1.addTab("result", null, jPanel4, null);
                {
                    jScrollPane2 = new JScrollPane();
                    jPanel4.add(jScrollPane2, BorderLayout.CENTER);
                    {

                        ListModel newRepListModel = new DefaultListModel();
                        newRepList = new JList();
                        jScrollPane2.setViewportView(newRepList);
                        newRepList.setModel(newRepListModel);
                        newRepList.addMouseListener(new MouseAdapter() {
                            static final String tortoiseMergeExe = "TortoiseMerge.exe";
                            static final String commandFormat = "cmd /c call \"%s\" /base:\"%s\" /theirs:\"%s\"";

                            public void mouseClicked(MouseEvent evt) {
                                if (!JListUtil.newInstance(newRepList).isCorrectMouseClick(evt)) {
                                    return;
                                }

                                OldNewFile oldNewFile = (OldNewFile) JListUtil
                                        .getLeadSelectionObject(newRepList);

                                String base = oldNewFile.newFile.getAbsolutePath();
                                String theirs = oldNewFile.oldFile.getAbsolutePath();

                                String command = String.format(commandFormat, tortoiseMergeExe, base, theirs);

                                System.out.println(command);

                                try {
                                    Runtime.getRuntime().exec(command);
                                } catch (IOException e) {
                                    JCommonUtil.handleException(e);
                                }
                            }
                        });
                        newRepList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                Object[] objects = (Object[]) newRepList.getSelectedValues();
                                if (objects == null || objects.length == 0) {
                                    return;
                                }
                                DefaultListModel model = (DefaultListModel) newRepList.getModel();
                                int lastIndex = model.getSize() - 1;
                                Object swap = null;

                                StringBuilder dsb = new StringBuilder();
                                for (Object current : objects) {
                                    int index = model.indexOf(current);
                                    switch (evt.getKeyCode()) {
                                    case 38:// up
                                        if (index != 0) {
                                            swap = model.getElementAt(index - 1);
                                            model.setElementAt(swap, index);
                                            model.setElementAt(current, index - 1);
                                        }
                                        break;
                                    case 40:// down
                                        if (index != lastIndex) {
                                            swap = model.getElementAt(index + 1);
                                            model.setElementAt(swap, index);
                                            model.setElementAt(current, index + 1);
                                        }
                                        break;
                                    case 127:// del
                                        OldNewFile current_ = (OldNewFile) current;
                                        dsb.append(current_.newFile.getName() + "\t"
                                                + (current_.newFile.delete() ? "T" : "F") + "\n");
                                        current_.newFile.delete();
                                        model.removeElement(current);
                                    }
                                }

                                if (dsb.length() > 0) {
                                    JOptionPaneUtil.newInstance().iconInformationMessage()
                                            .showMessageDialog("del result!\n" + dsb, "DELETE");
                                }
                            }
                        });

                    }
                }
                {
                    replaceOrignFile = new JButton();
                    jPanel4.add(replaceOrignFile, BorderLayout.SOUTH);
                    replaceOrignFile.setText("replace orign file");
                    replaceOrignFile.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            DefaultListModel model = (DefaultListModel) newRepList.getModel();
                            StringBuilder sb = new StringBuilder();
                            for (int ii = 0; ii < model.size(); ii++) {
                                OldNewFile file = (OldNewFile) model.getElementAt(ii);
                                boolean delSuccess = false;
                                boolean renameSuccess = false;
                                if (delSuccess = file.oldFile.delete()) {
                                    renameSuccess = file.newFile.renameTo(file.oldFile);
                                }
                                sb.append(file.oldFile.getName() + " del:" + (delSuccess ? "T" : "F")
                                        + " rename:" + (renameSuccess ? "T" : "F") + "\n");
                            }
                            JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog(sb,
                                    getTitle());
                        }
                    });
                }
            }
            {
                jPanel5 = new JPanel();
                BorderLayout jPanel5Layout = new BorderLayout();
                jPanel5.setLayout(jPanel5Layout);
                jTabbedPane1.addTab("template", null, jPanel5, null);
                {
                    jScrollPane3 = new JScrollPane();
                    jPanel5.add(jScrollPane3, BorderLayout.CENTER);
                    {
                        templateList = new JList();
                        reloadTemplateList();
                        jScrollPane3.setViewportView(templateList);
                        templateList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                if (templateList.getLeadSelectionIndex() == -1) {
                                    return;
                                }
                                Entry<Object, Object> entry = (Entry<Object, Object>) JListUtil
                                        .getLeadSelectionObject(templateList);
                                repFromText.setText((String) entry.getKey());
                                repToText.setText((String) entry.getValue());
                            }
                        });
                        templateList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                JListUtil.newInstance(templateList).defaultJListKeyPressed(evt);
                            }
                        });
                    }
                }
                {
                    scheduleExecute = new JButton();
                    jPanel5.add(scheduleExecute, BorderLayout.SOUTH);
                    scheduleExecute.setText("schedule execute");
                    scheduleExecute.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            scheduleExecuteActionPerformed(evt);
                        }
                    });
                }
            }
        }
        this.setSize(512, 350);

        JCommonUtil.setFontAll(this.getRootPane());

        JCommonUtil.frameCloseDo(this, new WindowAdapter() {
            public void windowClosing(WindowEvent paramWindowEvent) {
                if (StringUtils.isNotBlank(repFromText.getText())) {
                    prop.put(repFromText.getText(), repToText.getText());
                }
                try {
                    prop.store(new FileOutputStream(propFile), "regexText");
                } catch (Exception e) {
                    JCommonUtil.handleException("properties store error!", e);
                }
                setVisible(false);
                dispose();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:uk.ac.lkl.cram.ui.ModuleFrame.java

/**
 * Creates new form ModuleFrame/*  ww  w  .  ja v  a2s.  co m*/
 * @param module the module that this window displays
 * @param file  
 */
public ModuleFrame(final Module module, File file) {
    this.module = module;
    this.moduleFile = file;
    this.setTitle(module.getModuleName());
    initComponents();
    //Add undo mechanism
    undoHandler = new UndoHandler();
    JMenuItem undoMI = editMenu.add(undoHandler.getUndoAction());
    JMenuItem redoMI = editMenu.add(undoHandler.getRedoAction());
    //Listen to the undo handler for when there is something to undo
    undoHandler.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            //We're assuming there's only one property
            //If the new value is true, then there's something to undo
            //And thus the save menu item should be enabled
            Boolean newValue = (Boolean) evt.getNewValue();
            if (moduleFile != null) {
                saveMI.setEnabled(newValue);
            }
        }
    });
    editMenu.addSeparator();
    //Add cut, copy & paste menu items
    JMenuItem cutMI = editMenu.add(new JMenuItem(new DefaultEditorKit.CutAction()));
    cutMI.setText("Cut");
    JMenuItem copyMI = editMenu.add(new JMenuItem(new DefaultEditorKit.CopyAction()));
    copyMI.setText("Copy");
    JMenuItem pasteMI = editMenu.add(new JMenuItem(new DefaultEditorKit.PasteAction()));
    pasteMI.setText("Paste");

    //Listen for changes to the shared selection model
    sharedSelectionModel.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            //Update the menu items
            modifyLineItemMI.setEnabled(evt.getNewValue() != null);
            removeLineItemMI.setEnabled(evt.getNewValue() != null);
        }
    });

    doubleClickListener = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            //If the user double clicks, then treat this as a shortcut to modify the selected line item
            if (e.getClickCount() == 2) {
                modifySelectedLineItem();
            }
        }
    };

    //Set Accelerator keys
    undoMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    redoMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    cutMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    copyMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    pasteMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    newMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    openMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    saveMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    quitMI.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    //Remove quit menu item and separator from file menu on Mac
    if (Utilities.isMac()) {
        fileMenu.remove(quitSeparator);
        fileMenu.remove(quitMI);
    }

    leftTaskPaneContainer.add(createCourseDataPane());
    leftTaskPaneContainer.add(createLineItemPane());
    leftTaskPaneContainer.add(createTutorHoursPane());
    leftTaskPaneContainer.add(createTutorCostPane());
    rightTaskPaneContainer.add(createLearningTypeChartPane());
    rightTaskPaneContainer.add(createLearningExperienceChartPane());
    rightTaskPaneContainer.add(createLearnerFeedbackChartPane());
    rightTaskPaneContainer.add(createHoursChartPane());
    rightTaskPaneContainer.add(createTotalCostsPane());
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopTree.java

@Override
public void setLookupSelectHandler(Runnable selectHandler) {
    impl.addMouseListener(new MouseAdapter() {
        @Override/* w w w . j a  v a  2  s  .  c  o  m*/
        public void mousePressed(MouseEvent e) {
            if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) {
                int rowForLocation = impl.getRowForLocation(e.getX(), e.getY());
                TreePath pathForLocation = impl.getPathForRow(rowForLocation);
                if (pathForLocation != null) {
                    CollectionDatasource treeCds = getDatasource();
                    if (treeCds != null) {
                        TreeModelAdapter.Node treeItem = (TreeModelAdapter.Node) pathForLocation
                                .getLastPathComponent();
                        if (treeItem != null) {
                            treeCds.setItem(treeItem.getEntity());
                            selectHandler.run();
                        }
                    }
                }
            }
        }
    });
}

From source file:de.tbuchloh.kiskis.gui.treeview.TreeView.java

/**
 * @param treeContext/*  w  ww.  j a  va2 s .  co  m*/
 */
public TreeView(final JPopupMenu treeContext) {
    final GroupNode root = new GroupNode();
    root.setModelNode(new Group());
    _treeModel = new DefaultTreeModel(root);
    setModel(_treeModel);

    this.setEditable(true);
    this.setCellRenderer(new SpecialNodeCellRenderer());
    this.setCellEditor(new NameCellEditor());
    this.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(final MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3) {
                LOG.debug("Context Menu invoked!"); //$NON-NLS-1$
                treeContext.show(TreeView.this, e.getX(), e.getY());
            }
        }
    });
    setDragEnabled(true);
    setAutoscrolls(true);
}

From source file:gui.DownloadPanel.java

public DownloadPanel(JFrame parent, String databasePath, int connectionTimeout, int readTimeout) {
    this.parent = parent;
    setLayout(new BorderLayout());

    this.connectionTimeout = connectionTimeout;
    this.readTimeout = readTimeout;

    downloadDialogs = new ArrayList<>();

    String connectionUrl = "jdbc:sqlite:" + databasePath + File.separator + "cheetah.db";
    databaseController = new DatabaseControllerImpl("org.sqlite.JDBC", connectionUrl, 0, "", "");

    try {//from   w w w .j ava 2  s.  co m
        databaseController.createTablesIfNotExist();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // Set up Downloads table.
    downloadsTableModel = new DownloadsTableModel();
    downloadTable = new JTable(downloadsTableModel);
    popup = initPopupMenu();

    downloadTable.getSelectionModel().addListSelectionListener(e -> {
        tableSelectionChanged();
        if (downloadPanelListener != null)
            downloadPanelListener.downloadSelected(selectedDownload);
    });

    // Allow only one row at a time to be selected.
    downloadTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Set up ProgressBar as renderer for progress column.
    ProgressRenderer renderer = new ProgressRenderer(0, 100);
    renderer.setStringPainted(true); // show progress text
    downloadTable.setDefaultRenderer(JProgressBar.class, renderer);

    // Set table's row height large enough to fit JProgressBar.
    downloadTable.setRowHeight((int) renderer.getPreferredSize().getHeight());

    downloadTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            super.mousePressed(e);
            int row = downloadTable.rowAtPoint(e.getPoint());
            downloadTable.getSelectionModel().setSelectionInterval(row, row);
            DownloadDialog downloadDialog = getDownloadDialogByDownload(selectedDownload);
            if (e.getButton() == MouseEvent.BUTTON3) { // TODO right click
                popup.show(downloadTable, e.getX(), e.getY());
            } else if (e.getClickCount() == 2) { // double click
                if (!downloadDialog.isVisible()) {
                    downloadDialog.setVisible(true);
                }
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(downloadTable);
    scrollPane.getViewport().setBackground(Color.WHITE);
    add(scrollPane, BorderLayout.CENTER);

    try {
        downloadList = databaseController.load();
    } catch (Exception e) {
        e.printStackTrace();
    }

    DownloadDialog downloadDialog;
    for (Download download : downloadList) {
        calculateDownloaded(download);
        download.setDownloadInfoListener(this);
        download.addDownloadStatusListener(this);
        downloadDialog = new DownloadDialog(parent, download);
        downloadDialog.setDownloadInfoListener(this);
        downloadDialogs.add(downloadDialog);
        downloadsTableModel.addDownload(download);
        downloadDialog.setDownloadRanges(download.getDownloadRangeList());
    }
    setColumnWidths();
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected void attachDoubleClickListenerToTree() {
    MouseListener ml = new MouseAdapter() {
        @Override//ww  w  .ja v  a2 s .  c  om
        public void mousePressed(MouseEvent e) {
            int selRow = currentTree.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = currentTree.getPathForLocation(e.getX(), e.getY());
            if (selRow != -1 && ((DefaultMutableTreeNode) selPath.getLastPathComponent()).isLeaf()) {
                if (e.getClickCount() == 2) {
                    playSelectedTreeSound(selPath, Paths.get(vpkPath));
                }
            }
        }
    };
    currentTree.addMouseListener(ml);
}

From source file:edu.harvard.mcz.imagecapture.DeterminationFrame.java

/**
 * This method initializes jTable   /* w  w w  .j  a  v a 2 s  . c  o  m*/
 *    
 * @return javax.swing.JTable   
 */
private JTable getJTable() {
    if (jTableDeterminations == null) {
        jTableDeterminations = new JTable();
        DeterminationTableModel model = new DeterminationTableModel();
        jTableDeterminations.setModel(model);
        if (determinations != null) {
            jTableDeterminations.setModel(determinations);
        }

        FilteringAgentJComboBox field = new FilteringAgentJComboBox();
        jTableDeterminations.getColumnModel().getColumn(DeterminationTableModel.ROW_IDENTIFIEDBY)
                .setCellEditor(new ComboBoxCellEditor(field));

        setTableColumnEditors();

        jTableDeterminations.setRowHeight(jTableDeterminations.getRowHeight() + 4);

        jTableDeterminations.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    clickedOnDetsRow = ((JTable) e.getComponent()).getSelectedRow();
                    jPopupDets.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    clickedOnDetsRow = ((JTable) e.getComponent()).getSelectedRow();
                    jPopupDets.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        jPopupDets = new JPopupMenu();
        JMenuItem mntmDeleteRow = new JMenuItem("Delete Row");
        mntmDeleteRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    log.debug(clickedOnDetsRow);
                    if (clickedOnDetsRow >= 0) {
                        int ok = JOptionPane.showConfirmDialog(thisFrame, "Delete the selected determination?",
                                "Delete Determination", JOptionPane.OK_CANCEL_OPTION);
                        if (ok == JOptionPane.OK_OPTION) {
                            log.debug("deleting determination row " + clickedOnDetsRow);
                            ((DeterminationTableModel) jTableDeterminations.getModel())
                                    .deleteRow(clickedOnDetsRow);
                        } else {
                            log.debug("determination row delete canceled by user.");
                        }
                    } else {
                        JOptionPane.showMessageDialog(thisFrame, "Unable to select row to delete.");
                    }
                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    JOptionPane.showMessageDialog(thisFrame,
                            "Failed to delete a determination row. " + ex.getMessage());
                }
            }
        });
        jPopupDets.add(mntmDeleteRow);

    }
    return jTableDeterminations;
}