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:display.containers.FileManager.java

public Container getPane() {
    //if (gui==null) {

    fileSystemView = FileSystemView.getFileSystemView();
    desktop = Desktop.getDesktop();

    JPanel detailView = new JPanel(new BorderLayout(3, 3));
    //fileTableModel = new FileTableModel();

    table = new JTable();
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setAutoCreateRowSorter(true);/*from  w  ww.  j a v a  2s.c o m*/
    table.setShowVerticalLines(false);
    table.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                Point p = e.getPoint();
                int row = table.convertRowIndexToModel(table.rowAtPoint(p));
                int column = table.convertColumnIndexToModel(table.columnAtPoint(p));
                if (row >= 0 && column >= 0) {
                    mouseDblClicked(row, column);
                }
            }
        }
    });
    table.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            if (KeyEvent.VK_DELETE == arg0.getKeyCode()) {
                if (mode != 2) {
                    parentFrame.setLock(true);
                    parentFrame.getProgressBarPanel().setVisible(true);
                    Thread t = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                deleteSelectedFiles();
                            } catch (IOException e) {
                                JOptionPane.showMessageDialog(parentFrame, "Error during the deletion.",
                                        "Deletion error", JOptionPane.ERROR_MESSAGE);
                                WindowManager.mwLogger.log(Level.SEVERE, "Error during the deletion.", e);
                            } finally {
                                parentFrame.setLock(false);
                                refresh();
                                parentFrame.getProgressBarPanel().setVisible(false);
                            }
                        }
                    });
                    t.start();

                } else {
                    if (UserProfile.CURRENT_USER.getLevel() == 3) {
                        parentFrame.setLock(true);
                        parentFrame.getProgressBarPanel().setVisible(true);
                        Thread delThread = new Thread(new Runnable() {

                            @Override
                            public void run() {
                                int[] rows = table.getSelectedRows();
                                int[] columns = table.getSelectedColumns();
                                for (int i = 0; i < rows.length; i++) {
                                    if (!continueAction) {
                                        continueAction = true;
                                        return;
                                    }
                                    int row = table.convertRowIndexToModel(rows[i]);
                                    try {
                                        deleteServerFile(row);
                                    } catch (Exception e) {
                                        WindowManager.mwLogger.log(Level.SEVERE, "Error during the deletion.",
                                                e);
                                    }
                                }
                                refresh();
                                parentFrame.setLock(false);
                                parentFrame.getProgressBarPanel().setVisible(false);
                            }
                        });
                        delThread.start();

                    }
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    });
    table.getSelectionModel().addListSelectionListener(listSelectionListener);
    JScrollPane tableScroll = new JScrollPane(table);
    Dimension d = tableScroll.getPreferredSize();
    tableScroll.setPreferredSize(new Dimension((int) d.getWidth(), (int) d.getHeight() / 2));
    detailView.add(tableScroll, BorderLayout.CENTER);

    // the File tree
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    treeModel = new DefaultTreeModel(root);
    table.getRowSorter().addRowSorterListener(new RowSorterListener() {

        @Override
        public void sorterChanged(RowSorterEvent e) {
            ((FileTableModel) table.getModel()).fireTableDataChanged();
        }
    });

    // show the file system roots.
    File[] roots = fileSystemView.getRoots();
    for (File fileSystemRoot : roots) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);
        root.add(node);
        //showChildren(node);
        //
        File[] files = fileSystemView.getFiles(fileSystemRoot, true);
        for (File file : files) {
            if (file.isDirectory()) {
                node.add(new DefaultMutableTreeNode(file));
            }
        }
        //
    }
    JScrollPane treeScroll = new JScrollPane();

    Dimension preferredSize = treeScroll.getPreferredSize();
    Dimension widePreferred = new Dimension(200, (int) preferredSize.getHeight());
    treeScroll.setPreferredSize(widePreferred);

    JPanel fileView = new JPanel(new BorderLayout(3, 3));

    detailView.add(fileView, BorderLayout.SOUTH);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroll, detailView);

    JPanel simpleOutput = new JPanel(new BorderLayout(3, 3));
    progressBar = new JProgressBar();
    simpleOutput.add(progressBar, BorderLayout.EAST);
    progressBar.setVisible(false);
    showChildren(getCurrentDir().toPath());
    //table.setDragEnabled(true);
    table.setColumnSelectionAllowed(false);

    // Menu popup
    Pmenu = new JPopupMenu();
    changeProjectitem = new JMenuItem("Reassign");
    renameProjectitem = new JMenuItem("Rename");
    twitem = new JMenuItem("To workspace");
    tlitem = new JMenuItem("To local");
    processitem = new JMenuItem("Select for process");
    switch (mode) {
    case 0:
        Pmenu.add(twitem);
        twitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtnlocalTowork().doClick();
            }
        });
        break;
    case 1:
        Pmenu.add(tlitem);
        Pmenu.add(processitem);
        tlitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtnWorkTolocal().doClick();
            }
        });
        processitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        // Recupere les lignes selectionnees
                        int[] indices = table.getSelectedRows();
                        // On recupere les fichiers correspondants
                        ArrayList<File> files = new ArrayList<File>();
                        for (int i = 0; i < indices.length; i++) {
                            int row = table.convertRowIndexToModel(indices[i]);
                            File fi = ((FileTableModel) table.getModel()).getFile(row);
                            if (fi.isDirectory())
                                files.add(fi);
                        }
                        ImageProcessingFrame imf = new ImageProcessingFrame(files);
                    }
                });

            }
        });
        break;
    case 2:
        if (UserProfile.CURRENT_USER.getLevel() == 3) {
            Pmenu.add(changeProjectitem);
            Pmenu.add(renameProjectitem);
        }
        Pmenu.add(twitem);
        twitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtndistToWorkspace().doClick();
            }
        });
        Pmenu.add(tlitem);
        tlitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtndistToLocal().doClick();
            }
        });
        break;
    }
    changeProjectitem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            table.setEnabled(false);
            File from = ((FileTableModel) table.getModel())
                    .getFile(table.convertRowIndexToModel(table.getSelectedRows()[0]));

            ReassignProjectPanel reas = new ReassignProjectPanel(from.toPath()); // mode creation de liens
            Popup popup = PopupFactory.getSharedInstance().getPopup(WindowManager.MAINWINDOW, reas,
                    (int) WindowManager.MAINWINDOW.getX() + 200, (int) WindowManager.MAINWINDOW.getY() + 150);
            reas.setPopupWindow(popup);
            popup.show();
            table.setEnabled(true);
        }
    });
    renameProjectitem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            table.setEnabled(false);
            final File from = ((FileTableModel) table.getModel())
                    .getFile(table.convertRowIndexToModel(table.getSelectedRows()[0]));
            JDialog.setDefaultLookAndFeelDecorated(true);
            String s = (String) JOptionPane.showInputDialog(WindowManager.MAINWINDOW, "New project name ?",
                    "Rename project", JOptionPane.PLAIN_MESSAGE, null, null, from.getName());

            //If a string was returned, say so.
            if ((s != null) && (s.length() > 0)) {
                ProjectDAO pdao = new MySQLProjectDAO();
                if (new File(from.getParent() + File.separator + s).exists()) {
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            JDialog.setDefaultLookAndFeelDecorated(true);
                            JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                    "Couldn't rename " + from.getName()
                                            + " (A file with this filename already exists)",
                                    "Renaming error", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                    WindowManager.mwLogger.log(Level.SEVERE,
                            "Error during file project renaming (" + from.getName() + "). [Duplication error]");
                } else {
                    try {
                        boolean succeed = pdao.renameProject(from.getName(), s);
                        if (!succeed) {
                            SwingUtilities.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    JDialog.setDefaultLookAndFeelDecorated(true);
                                    JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                            "Couldn't rename " + from.getName()
                                                    + " (no project with this name)",
                                            "Renaming error", JOptionPane.ERROR_MESSAGE);
                                }
                            });
                        } else {
                            from.renameTo(new File(from.getParent() + File.separator + s));
                            // on renomme le repertoire nifti ou dicom correspondant si il existe
                            switch (from.getParentFile().getName()) {
                            case ServerInfo.NRI_ANALYSE_NAME:
                                if (new File(from.getAbsolutePath().replaceAll(ServerInfo.NRI_ANALYSE_NAME,
                                        ServerInfo.NRI_DICOM_NAME)).exists())
                                    try {
                                        Files.move(Paths.get(from.getAbsolutePath().replaceAll(
                                                ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)),
                                                Paths.get(from.getParent().replaceAll(
                                                        ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)
                                                        + File.separator + s));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        SwingUtilities.invokeLater(new Runnable() {

                                            @Override
                                            public void run() {
                                                JDialog.setDefaultLookAndFeelDecorated(true);
                                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                                        "Couldn't rename " + from.getName()
                                                                + " (error with file system)",
                                                        "Renaming error", JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                        WindowManager.mwLogger.log(Level.SEVERE,
                                                "Error during file project renaming (" + from.getName() + ")",
                                                e);
                                    } //from.renameTo(new File(from.getParent().replaceAll(ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)+File.separator+s));
                                break;
                            case ServerInfo.NRI_DICOM_NAME:
                                if (new File(from.getAbsolutePath().replaceAll(ServerInfo.NRI_DICOM_NAME,
                                        ServerInfo.NRI_ANALYSE_NAME)).exists())
                                    try {
                                        Files.move(Paths.get(from.getAbsolutePath().replaceAll(
                                                ServerInfo.NRI_DICOM_NAME, ServerInfo.NRI_ANALYSE_NAME)),
                                                Paths.get(from.getParent().replaceAll(ServerInfo.NRI_DICOM_NAME,
                                                        ServerInfo.NRI_ANALYSE_NAME) + File.separator + s));
                                    } catch (IOException e) {
                                        SwingUtilities.invokeLater(new Runnable() {

                                            @Override
                                            public void run() {
                                                JDialog.setDefaultLookAndFeelDecorated(true);
                                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                                        "Couldn't rename " + from.getName()
                                                                + " (error with file system)",
                                                        "Renaming error", JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                        e.printStackTrace();
                                        WindowManager.mwLogger.log(Level.SEVERE,
                                                "Error during file project renaming (" + from.getName() + ")",
                                                e);
                                    } //from.renameTo(new File(from.getParent().replaceAll(ServerInfo.NRI_DICOM_NAME, ServerInfo.NRI_ANALYSE_NAME)+File.separator+s));
                                break;
                            }
                            refresh();
                        }
                    } catch (final SQLException e) {
                        WindowManager.mwLogger.log(Level.SEVERE, "Error during SQL project renaming", e);
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                JDialog.setDefaultLookAndFeelDecorated(true);
                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                        "Exception : " + e.toString(), "Openning error",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                }
            }
            table.setEnabled(true);
        }
    });
    table.addMouseListener(new MouseListener() {

        public void mouseClicked(MouseEvent me) {

        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent me) {
            if (me.getButton() == 3 && table.getSelectedRowCount() > 0) {
                int row = table.convertRowIndexToModel(table.rowAtPoint(me.getPoint()));
                changeProjectitem.setVisible(isPatient(((FileTableModel) table.getModel()).getFile(row)));
                renameProjectitem.setVisible(isProject(((FileTableModel) table.getModel()).getFile(row)));
                Pmenu.show(me.getComponent(), me.getX(), me.getY());
            }
        }
    });
    //

    //}
    return tableScroll;
}

From source file:io.github.jeremgamer.editor.panels.Panels.java

public Panels(final JFrame frame, final PanelsPanel pp) {
    this.setBorder(BorderFactory.createTitledBorder(""));

    JButton add = null;//from w  w  w .  ja  v  a  2s  . c  om
    try {
        add = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("add.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                JOptionPane jop = new JOptionPane();
                @SuppressWarnings("static-access")
                String name = jop.showInputDialog((JFrame) SwingUtilities.windowForComponent(panelList),
                        "Nommez le panneau :", "Crer un panneau", JOptionPane.QUESTION_MESSAGE);

                if (name != null) {
                    for (int i = 0; i < data.getSize(); i++) {
                        if (data.get(i).equals(name)) {
                            name += "1";
                        }
                    }
                    data.addElement(name);
                    new PanelSave(name);
                    PanelsPanel.updateLists();
                    mainPanel.addItem(name);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });

    JButton remove = null;
    try {
        remove = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    remove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                if (panelList.getSelectedValue() != null) {
                    File file = new File("projects/" + Editor.getProjectName() + "/panels/"
                            + panelList.getSelectedValue() + "/" + panelList.getSelectedValue() + ".rbd");
                    JOptionPane jop = new JOptionPane();
                    @SuppressWarnings("static-access")
                    int option = jop.showConfirmDialog((JFrame) SwingUtilities.windowForComponent(panelList),
                            "tes-vous sr de vouloir supprimer ce panneau?", "Avertissement",
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

                    if (option == JOptionPane.OK_OPTION) {
                        if (panelList.getSelectedValue().equals(pp.getFileName())) {
                            pp.setFileName("");
                        }
                        pp.hide();
                        file.delete();
                        File parent = new File(file.getParent());
                        for (File img : FileUtils.listFiles(parent, TrueFileFilter.INSTANCE,
                                TrueFileFilter.INSTANCE)) {
                            img.delete();
                        }
                        parent.delete();
                        mainPanel.removeItem(panelList.getSelectedValue());
                        data.remove(panelList.getSelectedIndex());
                        ActionPanel.updateLists();
                        PanelsPanel.updateLists();
                    }
                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            }

        }

    });

    JPanel buttons = new JPanel();
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
    buttons.add(add);
    buttons.add(remove);

    mainPanel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            @SuppressWarnings("unchecked")
            JComboBox<String> combo = (JComboBox<String>) event.getSource();
            GeneralSave gs = new GeneralSave();
            try {
                gs.load(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                gs.set("mainPanel", combo.getSelectedItem());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    });

    updateList();
    panelList.addMouseListener(new MouseAdapter() {
        @SuppressWarnings("unchecked")
        public void mouseClicked(MouseEvent evt) {
            JList<String> list = (JList<String>) evt.getSource();
            if (evt.getClickCount() == 2) {
                int index = list.locationToIndex(evt.getPoint());
                if (isOpen == false) {
                    pp.load(new File("projects/" + Editor.getProjectName() + "/panels/"
                            + list.getModel().getElementAt(index) + "/" + list.getModel().getElementAt(index)
                            + ".rbd"));
                    PanelsPanel.updateLists();
                    pp.show();
                    previousSelection = list.getSelectedValue();
                    isOpen = true;
                } else {
                    try {
                        if (previousSelection.equals(list.getModel().getElementAt(index))) {
                            pp.hide();
                            previousSelection = list.getSelectedValue();
                            list.clearSelection();
                            isOpen = false;
                        } else {
                            pp.hideThenShow();
                            previousSelection = list.getSelectedValue();
                            pp.load(new File("projects/" + Editor.getProjectName() + "/panels/"
                                    + list.getModel().getElementAt(index) + "/"
                                    + list.getModel().getElementAt(index) + ".rbd"));
                            PanelsPanel.updateLists();
                        }
                    } catch (NullPointerException npe) {
                        pp.hide();
                        list.clearSelection();
                    }
                }
            } else if (evt.getClickCount() == 3) {
                int index = list.locationToIndex(evt.getPoint());
                if (isOpen == false) {
                    pp.load(new File("projects/" + Editor.getProjectName() + "/panels/"
                            + list.getModel().getElementAt(index) + "/" + list.getModel().getElementAt(index)
                            + ".rbd"));
                    PanelsPanel.updateLists();
                    pp.show();
                    previousSelection = list.getSelectedValue();
                    isOpen = true;
                } else {
                    try {
                        if (previousSelection.equals(list.getModel().getElementAt(index))) {
                            pp.hide();
                            previousSelection = list.getSelectedValue();
                            list.clearSelection();
                            isOpen = false;
                        } else {
                            pp.hideThenShow();
                            previousSelection = list.getSelectedValue();
                            pp.load(new File("projects/" + Editor.getProjectName() + "/panels/"
                                    + list.getModel().getElementAt(index) + "/"
                                    + list.getModel().getElementAt(index) + ".rbd"));
                            PanelsPanel.updateLists();
                        }
                    } catch (NullPointerException npe) {
                        pp.hide();
                        list.clearSelection();
                    }
                }
            }
        }
    });
    JScrollPane listPane = new JScrollPane(panelList);
    listPane.getVerticalScrollBar().setUnitIncrement(Editor.SCROLL_SPEED);
    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    this.add(buttons);
    this.add(listPane);

    JPanel mainPanelInput = new JPanel();
    mainPanelInput.setPreferredSize(new Dimension(280, 35));
    mainPanelInput.setMaximumSize(new Dimension(280, 35));
    mainPanelInput.add(new JLabel("Panneau principal:"));
    mainPanel.setPreferredSize(new Dimension(150, 27));
    mainPanelInput.add(mainPanel);
    this.add(mainPanelInput);
}

From source file:GUI.ListOfOffres1.java

private static WebPanel createOffresPanel(final String url, final String title, String body, final int id,
        final int myId) throws IOException {

    final WebPanel offresPanel = new WebPanel(true);
    offresPanel.setPaintFocus(false);/*from  w ww  .  j  av a2s . c  o  m*/
    WebLookAndFeel.install();
    WebLookAndFeel.setDecorateAllWindows(true);
    offresPanel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            // Opening dialog
            Icon blueIcon = new ImageIcon("yourFile.gif");
            Object stringArray[] = { "Ovrir", "No" };
            int returnValue = JOptionPane.showOptionDialog(offresPanel, "Ouvrir Offre?",
                    "Vous voulez ouvrir une offre", JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, blueIcon, stringArray, stringArray[0]);
            switch (returnValue) {
            //                            case 0 :
            //                                openPleaseWait();
            //                                try {
            //                                    System.out.print("tehe id is :"+id);
            //                                    new OffreDAO().deleteOffre(id);
            //                                    openListOfOffresFrameagn(0,"");
            //                                } catch (IOException ex) {
            //                                    Logger.getLogger(ListOfOffres1.class.getName()).log(Level.SEVERE, null, ex);
            //                                }
            case 0:
                System.out.println("The return value" + returnValue);

                try {
                    //openPleaseWait();
                    new OneOffre().openListOfOffresFrameagn(id, myId);
                } catch (IOException ex) {
                    Logger.getLogger(ListOfOffres1.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            System.out.println("The return value" + returnValue);
            WebLookAndFeel.setDecorateDialogs(true);
        }
    });

    final WebPanel descPanel = new WebPanel(false);

    descPanel.add();
    descPanel.setOpaque(true);
    WebLabel descLabel = new WebLabel("<html>\n" + "<body>\n" + "\n" + "<h2>" + title + "</h2>\n" + "\n" + "<p>"
            + body + "</p>\n" + "\n" + "</body>\n" + "</html>");

    descPanel.add(descLabel);
    offresPanel.setPaintFocus(true);
    offresPanel.setMargin(10);
    // load the image once
    try {
        BufferedImage bi = ImageIO.read(new URL(url));
        ImageIcon img = new ImageIcon(bi);
        WebDecoratedImage img2 = new WebDecoratedImage(img);
        img2.setShadeWidth(0);
        offresPanel.add(img2);
        offresPanel.setPreferredSize(new Dimension(300, 400));
        GridLayout layoutPffresPanel = new GridLayout(2, 1);
        offresPanel.setLayout(layoutPffresPanel);
        offresPanel.add(descPanel);
    } catch (IOException e) {
        //or open no image found image
        BufferedImage image = ImageIO.read(new File("resources/no-image-found.jpg"));
        ImageIcon i1 = new ImageIcon(image);
        WebDecoratedImage img2 = new WebDecoratedImage(i1);
        img2.setShadeWidth(0);
        offresPanel.add(img2);
        offresPanel.setPreferredSize(new Dimension(300, 400));
        GridLayout layoutPffresPanel = new GridLayout(2, 1);
        offresPanel.setLayout(layoutPffresPanel);
        offresPanel.add(descPanel);
    }
    return offresPanel;
}

From source file:com._17od.upm.gui.AccountDialog.java

public AccountDialog(AccountInformation account, JFrame parentWindow, boolean readOnly,
        ArrayList existingAccounts) {
    super(parentWindow, true);

    boolean addingAccount = false;

    //Request focus on Account JDialog when mouse clicked
    this.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 1) {
                requestFocus();//from  ww w. j ava  2 s  .  c  o m

            }
        }
    });

    // Set the title based on weather we've been opened in readonly mode and
    // weather the
    // Account passed in is empty or not
    String title = null;
    if (readOnly) {
        title = Translator.translate("viewAccount");
    } else if (!readOnly && account.getAccountName().trim().equals("")) {
        title = Translator.translate("addAccount");
        addingAccount = true;
    } else {
        title = Translator.translate("editAccount");
    }
    setTitle(title);

    this.pAccount = account;
    this.existingAccounts = existingAccounts;
    this.parentWindow = parentWindow;

    getContentPane().setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    Container container = getContentPane();

    // The AccountName Row
    JLabel accountLabel = new JLabel(Translator.translate("account"));
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    container.add(accountLabel, c);

    // This panel will hold the Account field and the copy and paste
    // buttons.
    JPanel accountPanel = new JPanel(new GridBagLayout());

    accountName = new JTextField(new String(pAccount.getAccountName()), 20);
    if (readOnly) {
        accountName.setEditable(false);
    }
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    accountPanel.add(accountName, c);
    accountName.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            accountName.selectAll();
        }
    });

    JButton acctCopyButton = new JButton();
    acctCopyButton.setIcon(Util.loadImage("copy-icon.png"));
    acctCopyButton.setToolTipText("Copy");
    acctCopyButton.setEnabled(true);
    acctCopyButton.setMargin(new Insets(0, 0, 0, 0));
    acctCopyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            copyTextField(accountName);
        }
    });
    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    accountPanel.add(acctCopyButton, c);

    JButton acctPasteButton = new JButton();
    acctPasteButton.setIcon(Util.loadImage("paste-icon.png"));
    acctPasteButton.setToolTipText("Paste");
    acctPasteButton.setEnabled(!readOnly);
    acctPasteButton.setMargin(new Insets(0, 0, 0, 0));
    acctPasteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            pasteToTextField(accountName);
        }
    });
    c.gridx = 2;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    accountPanel.add(acctPasteButton, c);

    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    container.add(accountPanel, c);

    // Userid Row
    JLabel useridLabel = new JLabel(Translator.translate("userid"));
    c.gridx = 0;
    c.gridy = 1;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    container.add(useridLabel, c);

    // This panel will hold the User ID field and the copy and paste
    // buttons.
    JPanel idPanel = new JPanel(new GridBagLayout());

    userId = new JTextField(new String(pAccount.getUserId()), 20);
    if (readOnly) {
        userId.setEditable(false);
    }
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    idPanel.add(userId, c);
    userId.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            userId.selectAll();
        }
    });

    JButton idCopyButton = new JButton();
    idCopyButton.setIcon(Util.loadImage("copy-icon.png"));
    idCopyButton.setToolTipText("Copy");
    idCopyButton.setEnabled(true);
    idCopyButton.setMargin(new Insets(0, 0, 0, 0));
    idCopyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            copyTextField(userId);
        }
    });
    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    idPanel.add(idCopyButton, c);

    JButton idPasteButton = new JButton();
    idPasteButton.setIcon(Util.loadImage("paste-icon.png"));
    idPasteButton.setToolTipText("Paste");
    idPasteButton.setEnabled(!readOnly);
    idPasteButton.setMargin(new Insets(0, 0, 0, 0));
    idPasteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            pasteToTextField(userId);
        }
    });
    c.gridx = 2;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    idPanel.add(idPasteButton, c);

    c.gridx = 1;
    c.gridy = 1;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    container.add(idPanel, c);

    // Password Row
    JLabel passwordLabel = new JLabel(Translator.translate("password"));
    c.gridx = 0;
    c.gridy = 2;
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    c.insets = new Insets(15, 10, 10, 10);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    container.add(passwordLabel, c);

    // This panel will hold the password, generate password button, copy and
    // paste buttons, and hide password checkbox
    JPanel passwordPanel = new JPanel(new GridBagLayout());

    password = new JPasswordField(new String(pAccount.getPassword()), 20);
    // allow CTRL-C on the password field
    password.putClientProperty("JPasswordField.cutCopyAllowed", Boolean.TRUE);
    password.setEditable(!readOnly);
    password.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            password.selectAll();
        }
    });
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 1;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    passwordPanel.add(password, c);

    JButton generateRandomPasswordButton = new JButton(Translator.translate("generate"));
    if (readOnly) {
        generateRandomPasswordButton.setEnabled(false);
    }
    generateRandomPasswordButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionevent) {
            // Get the user's preference about including or not Escape
            // Characters to generated passwords
            Boolean includeEscapeChars = new Boolean(
                    Preferences.get(Preferences.ApplicationOptions.INCLUDE_ESCAPE_CHARACTERS, "true"));
            int pwLength = Preferences.getInt(Preferences.ApplicationOptions.ACCOUNT_PASSWORD_LENGTH, 8);
            String Password;

            if ((includeEscapeChars.booleanValue()) && (pwLength > 3)) {
                // Verify that the generated password satisfies the criteria
                // for strong passwords(including Escape Characters)
                do {
                    Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue());
                } while (!(CheckPassStrong(Password, includeEscapeChars.booleanValue())));

            } else if (!(includeEscapeChars.booleanValue()) && (pwLength > 2)) {
                // Verify that the generated password satisfies the criteria
                // for strong passwords(excluding Escape Characters)
                do {
                    Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue());
                } while (!(CheckPassStrong(Password, includeEscapeChars.booleanValue())));

            } else {
                // Else a weak password of 3 or less chars will be produced
                Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue());
            }
            password.setText(Password);
        }
    });
    if (addingAccount) {
        generateRandomPasswordButton.doClick();
    }
    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    passwordPanel.add(generateRandomPasswordButton, c);

    JButton pwCopyButton = new JButton();
    pwCopyButton.setIcon(Util.loadImage("copy-icon.png"));
    pwCopyButton.setToolTipText("Copy");
    pwCopyButton.setEnabled(true);
    pwCopyButton.setMargin(new Insets(0, 0, 0, 0));
    pwCopyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            copyTextField(password);
        }
    });
    c.gridx = 2;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    passwordPanel.add(pwCopyButton, c);

    JButton pwPasteButton = new JButton();
    pwPasteButton.setIcon(Util.loadImage("paste-icon.png"));
    pwPasteButton.setToolTipText("Paste");
    pwPasteButton.setEnabled(!readOnly);
    pwPasteButton.setMargin(new Insets(0, 0, 0, 0));
    pwPasteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            pasteToTextField(password);
        }
    });
    c.gridx = 3;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    passwordPanel.add(pwPasteButton, c);

    JCheckBox hidePasswordCheckbox = new JCheckBox(Translator.translate("hide"), true);
    defaultEchoChar = password.getEchoChar();
    hidePasswordCheckbox.setMargin(new Insets(5, 0, 5, 0));
    hidePasswordCheckbox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                password.setEchoChar(defaultEchoChar);
            } else {
                password.setEchoChar((char) 0);
            }
        }
    });

    Boolean hideAccountPassword = new Boolean(
            Preferences.get(Preferences.ApplicationOptions.ACCOUNT_HIDE_PASSWORD, "true"));
    hidePasswordCheckbox.setSelected(hideAccountPassword.booleanValue());

    c.gridx = 0;
    c.gridy = 1;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 0);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    passwordPanel.add(hidePasswordCheckbox, c);

    c.gridx = 1;
    c.gridy = 2;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 1;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    container.add(passwordPanel, c);

    // URL Row
    JLabel urlLabel = new JLabel(Translator.translate("url"));
    c.gridx = 0;
    c.gridy = 3;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    container.add(urlLabel, c);

    // This panel will hold the URL field and the copy and paste buttons.
    JPanel urlPanel = new JPanel(new GridBagLayout());

    url = new JTextField(new String(pAccount.getUrl()), 20);
    if (readOnly) {
        url.setEditable(false);
    }
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    urlPanel.add(url, c);
    url.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            url.selectAll();
        }
    });

    final JButton urlLaunchButton = new JButton();
    urlLaunchButton.setIcon(Util.loadImage("launch-url-sm.png"));
    urlLaunchButton.setToolTipText("Launch URL");
    urlLaunchButton.setEnabled(true);
    urlLaunchButton.setMargin(new Insets(0, 0, 0, 0));
    urlLaunchButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            String urlText = url.getText();

            // Check if the selected url is null or emty and inform the user
            // via JoptioPane message
            if ((urlText == null) || (urlText.length() == 0)) {
                JOptionPane.showMessageDialog(urlLaunchButton.getParent(),
                        Translator.translate("EmptyUrlJoptionpaneMsg"),
                        Translator.translate("UrlErrorJoptionpaneTitle"), JOptionPane.WARNING_MESSAGE);
                // Check if the selected url is a valid formated url(via
                // urlIsValid() method) and inform the user via JoptioPane
                // message
            } else if (!(urlIsValid(urlText))) {
                JOptionPane.showMessageDialog(urlLaunchButton.getParent(),
                        Translator.translate("InvalidUrlJoptionpaneMsg"),
                        Translator.translate("UrlErrorJoptionpaneTitle"), JOptionPane.WARNING_MESSAGE);
                // Call the method LaunchSelectedURL() using the selected
                // url as input
            } else {
                LaunchSelectedURL(urlText);
            }
        }
    });
    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    urlPanel.add(urlLaunchButton, c);

    JButton urlCopyButton = new JButton();
    urlCopyButton.setIcon(Util.loadImage("copy-icon.png"));
    urlCopyButton.setToolTipText("Copy");
    urlCopyButton.setEnabled(true);
    urlCopyButton.setMargin(new Insets(0, 0, 0, 0));
    urlCopyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            copyTextField(url);
        }
    });
    c.gridx = 2;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    urlPanel.add(urlCopyButton, c);

    JButton urlPasteButton = new JButton();
    urlPasteButton.setIcon(Util.loadImage("paste-icon.png"));
    urlPasteButton.setToolTipText("Paste");
    urlPasteButton.setEnabled(!readOnly);
    urlPasteButton.setMargin(new Insets(0, 0, 0, 0));
    urlPasteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            pasteToTextField(url);
        }
    });
    c.gridx = 3;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    urlPanel.add(urlPasteButton, c);

    c.gridx = 1;
    c.gridy = 3;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    container.add(urlPanel, c);

    // Notes Row
    JLabel notesLabel = new JLabel(Translator.translate("notes"));
    c.gridx = 0;
    c.gridy = 4;
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    container.add(notesLabel, c);

    // This panel will hold the Notes text area and the copy and paste
    // buttons.
    JPanel notesPanel = new JPanel(new GridBagLayout());

    notes = new JTextArea(new String(pAccount.getNotes()), 10, 20);
    if (readOnly) {
        notes.setEditable(false);
    }
    notes.setLineWrap(true); // Enable line wrapping.
    notes.setWrapStyleWord(true); // Line wrap at whitespace.
    JScrollPane notesScrollPane = new JScrollPane(notes);
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.BOTH;
    notesPanel.add(notesScrollPane, c);

    JButton notesCopyButton = new JButton();
    notesCopyButton.setIcon(Util.loadImage("copy-icon.png"));
    notesCopyButton.setToolTipText("Copy");
    notesCopyButton.setEnabled(true);
    notesCopyButton.setMargin(new Insets(0, 0, 0, 0));
    notesCopyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            copyTextArea(notes);
        }
    });
    c.gridx = 1;
    c.gridy = 0;
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    notesPanel.add(notesCopyButton, c);

    JButton notesPasteButton = new JButton();
    notesPasteButton.setIcon(Util.loadImage("paste-icon.png"));
    notesPasteButton.setToolTipText("Paste");
    notesPasteButton.setEnabled(!readOnly);
    notesPasteButton.setMargin(new Insets(0, 0, 0, 0));
    notesPasteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            pasteToTextArea(notes);
        }
    });
    c.gridx = 2;
    c.gridy = 0;
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    c.insets = new Insets(0, 0, 0, 5);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    notesPanel.add(notesPasteButton, c);

    c.gridx = 1;
    c.gridy = 4;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(10, 10, 10, 10);
    c.weightx = 1;
    c.weighty = 1;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    container.add(notesPanel, c);

    // Seperator Row
    JSeparator sep = new JSeparator();
    c.gridx = 0;
    c.gridy = 5;
    c.anchor = GridBagConstraints.PAGE_END;
    c.insets = new Insets(0, 0, 0, 0);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 3;
    c.fill = GridBagConstraints.HORIZONTAL;
    container.add(sep, c);

    // Button Row
    JPanel buttonPanel = new JPanel();
    JButton okButton = new JButton(Translator.translate("ok"));
    // Link Enter key to okButton
    getRootPane().setDefaultButton(okButton);
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            okButtonAction();
        }
    });
    buttonPanel.add(okButton);
    if (!readOnly) {
        JButton cancelButton = new JButton(Translator.translate("cancel"));
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                closeButtonAction();
            }
        });
        buttonPanel.add(cancelButton);
    }
    c.gridx = 0;
    c.gridy = 6;
    c.anchor = GridBagConstraints.PAGE_END;
    c.insets = new Insets(5, 0, 5, 0);
    c.weightx = 0;
    c.weighty = 0;
    c.gridwidth = 3;
    c.fill = GridBagConstraints.NONE;
    container.add(buttonPanel, c);
}

From source file:au.org.ala.delta.editor.ui.CharacterTree.java

public CharacterTree() {

    setToggleClickCount(0);/*from  w w  w.j  a  v a  2 s.  co m*/
    _characterListBehaviour = new CharacterListBehaviour();
    _stateListBehaviour = new StateListBehaviour();

    ToolTipManager.sharedInstance().registerComponent(this);

    addMouseListener(new MouseAdapter() {

        public void mousePressed(MouseEvent e) {
            if (_doubleProcessingMouseEvent) {
                return;
            }
            if (!isEditing()) {
                int selectedRow = getClosestRowForLocation(e.getX(), e.getY());

                if ((selectedRow >= 0) && (e.getClickCount() == 2) && SwingUtilities.isLeftMouseButton(e)) {
                    Action action = getActionMap().get(SELECTION_ACTION_KEY);
                    if (action != null) {
                        action.actionPerformed(new ActionEvent(this, -1, ""));
                    }
                }
            }
        }
    });

    addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {

            TreePath selection = e.getNewLeadSelectionPath();
            if (selection != null) {
                Object lastComponent = selection.getLastPathComponent();
                if (lastComponent instanceof DefaultMutableTreeNode) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastComponent;

                    if (node.isLeaf()) {
                        CharacterTree.super.setTransferHandler(_stateTransferHandler);
                    } else {
                        CharacterTree.super.setTransferHandler(_characterTransferHandler);
                    }
                }
            }
        }
    });

    ActionMap actionMap = Application.getInstance().getContext().getActionMap(this);

    javax.swing.Action find = actionMap.get("find");
    if (find != null) {
        getActionMap().put("find", find);
    }

    javax.swing.Action findNext = actionMap.get("findNext");
    if (findNext != null) {
        getActionMap().put("findNext", findNext);
    }

    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK), SELECTION_ACTION_KEY);

}

From source file:com.mirth.connect.client.ui.components.MirthTreeTable.java

@Override
public void setSortable(boolean enable) {
    super.setSortable(enable);

    JTableHeader header = getTableHeader();
    if (enable) {
        if (treeTableSortAdapter == null) {
            treeTableSortAdapter = new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (SwingUtilities.isLeftMouseButton(e)) {
                        JTableHeader h = (JTableHeader) e.getSource();
                        TableColumnModel columnModel = getColumnModel();

                        int viewColumn = h.columnAtPoint(e.getPoint());
                        int column = columnModel.getColumn(viewColumn).getModelIndex();

                        if (column != -1) {
                            beforeSort();

                            // Toggle sort order (ascending <-> descending)
                            SortableTreeTableModel model = (SortableTreeTableModel) getTreeTableModel();
                            model.setColumnAndToggleSortOrder(column);

                            // Set sorting icon and current column index
                            ((SortableHeaderCellRenderer) getTableHeader().getDefaultRenderer())
                                    .setSortingIcon(model.getSortOrder());
                            ((SortableHeaderCellRenderer) getTableHeader().getDefaultRenderer())
                                    .setColumnIndex(column);

                            saveSortPreferences(column);

                            afterSort();
                        }// www  . j a  va  2 s .c o m
                    }
                }
            };
            header.addMouseListener(treeTableSortAdapter);
        }
    } else {
        if (treeTableSortAdapter != null) {
            header.removeMouseListener(treeTableSortAdapter);
            treeTableSortAdapter = null;
        }
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchFormFrame.java

private void buildMenu() {
    JXTaskPane editPane = new JXTaskPane();
    editPane.setTitle("Bearbeiten");
    JXButton editButton = new JXButton(new ImageIcon("./graphics/icons/replace2.png"));
    editButton.setToolTipText("Die ausgewhlte Zeichnung bearbeiten");
    editButton.addMouseListener(new MouseAdapter() {

        @Override//from  www .ja v a2s  .  c o m
        public void mouseReleased(MouseEvent e) {
            showEditFrame();
        }
    });

    editPane.getContentPane().add(editButton);

    JXTaskPane transferPane = new JXTaskPane();
    transferPane.setTitle("bertragen");
    JXButton transferVillageList = new JXButton(
            new ImageIcon(DSWorkbenchChurchFrame.class.getResource("/res/ui/center_ingame.png")));
    transferVillageList.setToolTipText("Zentriert den Mittelpunkt der gewhlten Zeichnung im Spiel");
    transferVillageList.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseReleased(MouseEvent e) {
            centerFormInGame();
        }
    });
    transferPane.getContentPane().add(transferVillageList);
    if (!GlobalOptions.isMinimal()) {
        JXButton centerButton = new JXButton(
                new ImageIcon(DSWorkbenchFormFrame.class.getResource("/res/center_24x24.png")));
        centerButton.setToolTipText("Zentriert die Zeichnung auf der Hauptkarte");
        centerButton.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                centerFormOnMap();
            }
        });

        transferPane.getContentPane().add(centerButton);
    }

    JXTaskPane miscPane = new JXTaskPane();
    if (!GlobalOptions.isMinimal()) {
        miscPane.setTitle("Sonstiges");
        JXButton searchButton = new JXButton(new ImageIcon("./graphics/icons/search.png"));
        searchButton.setToolTipText("Lsst die gewhlten Zeichnungen auf der Hauptkarte kurz aufblinken");
        searchButton.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                showFormOnMap();
            }
        });
        miscPane.getContentPane().add(searchButton);
    }
    if (!GlobalOptions.isMinimal()) {
        centerPanel.setupTaskPane(editPane, transferPane, miscPane);
    } else {
        centerPanel.setupTaskPane(editPane, transferPane);
    }
}

From source file:io.github.jeremgamer.editor.panels.Labels.java

public Labels(final JFrame frame, final LabelPanel lp, final PanelSave ps) {
    this.frame = frame;

    this.setBorder(BorderFactory.createTitledBorder(""));
    JButton add = null;/* ww w .j  a v  a 2s  .co m*/
    try {
        add = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("add.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                JOptionPane jop = new JOptionPane();
                @SuppressWarnings("static-access")
                String name = jop.showInputDialog((JFrame) SwingUtilities.windowForComponent(labelList),
                        "Nommez le label :", "Crer un label", JOptionPane.QUESTION_MESSAGE);

                if (name != null) {
                    for (int i = 0; i < data.getSize(); i++) {
                        if (data.get(i).equals(name)) {
                            name += "1";
                        }
                    }
                    data.addElement(name);
                    new LabelSave(name);
                    ActionPanel.updateLists();
                    OtherPanel.updateLists();
                    PanelsPanel.updateLists();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });

    JButton remove = null;
    try {
        remove = new JButton(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
    } catch (IOException e) {
        e.printStackTrace();
    }
    remove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                if (labelList.getSelectedValue() != null) {
                    File file = new File("projects/" + Editor.getProjectName() + "/labels/"
                            + labelList.getSelectedValue() + ".rbd");
                    JOptionPane jop = new JOptionPane();
                    @SuppressWarnings("static-access")
                    int option = jop.showConfirmDialog((JFrame) SwingUtilities.windowForComponent(labelList),
                            "tes-vous sr de vouloir supprimer ce label?", "Avertissement",
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

                    if (option == JOptionPane.OK_OPTION) {
                        File dir = new File("projects/" + Editor.getProjectName() + "/panels");
                        for (File f : FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE,
                                TrueFileFilter.INSTANCE)) {
                            if (!f.isDirectory()) {
                                try {
                                    ps.load(f);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                for (String section : ps
                                        .getSectionsContaining(labelList.getSelectedValue() + " (Label)")) {
                                    ps.removeSection(section);
                                    try {
                                        ps.save(f);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        if (labelList.getSelectedValue().equals(lp.getFileName())) {
                            lp.setFileName("");
                        }
                        lp.hide();
                        file.delete();
                        data.remove(labelList.getSelectedIndex());
                        ActionPanel.updateLists();
                        OtherPanel.updateLists();
                        PanelsPanel.updateLists();
                    }
                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            }

        }

    });

    JPanel buttons = new JPanel();
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
    buttons.add(add);
    buttons.add(remove);

    updateList();
    labelList.addMouseListener(new MouseAdapter() {
        @SuppressWarnings("unchecked")
        public void mouseClicked(MouseEvent evt) {
            JList<String> list = (JList<String>) evt.getSource();
            if (evt.getClickCount() == 2) {
                int index = list.locationToIndex(evt.getPoint());
                if (isOpen == false) {
                    lp.show();
                    lp.load(new File("projects/" + Editor.getProjectName() + "/labels/"
                            + list.getModel().getElementAt(index) + ".rbd"));
                    previousSelection = list.getSelectedValue();
                    isOpen = true;
                } else {
                    try {
                        if (previousSelection.equals(list.getModel().getElementAt(index))) {
                            lp.hide();
                            previousSelection = list.getSelectedValue();
                            list.clearSelection();
                            isOpen = false;
                        } else {
                            lp.hideThenShow();
                            previousSelection = list.getSelectedValue();
                            lp.load(new File("projects/" + Editor.getProjectName() + "/labels/"
                                    + list.getModel().getElementAt(index) + ".rbd"));
                        }
                    } catch (NullPointerException npe) {
                        lp.hide();
                        list.clearSelection();
                    }
                }
            } else if (evt.getClickCount() == 3) {
                int index = list.locationToIndex(evt.getPoint());
                if (isOpen == false) {
                    lp.show();
                    lp.load(new File("projects/" + Editor.getProjectName() + "/labels/"
                            + list.getModel().getElementAt(index) + ".rbd"));
                    previousSelection = list.getSelectedValue();
                    isOpen = true;
                } else {
                    try {
                        if (previousSelection.equals(list.getModel().getElementAt(index))) {
                            lp.hide();
                            previousSelection = list.getSelectedValue();
                            list.clearSelection();
                            isOpen = false;
                        } else {
                            lp.hideThenShow();
                            previousSelection = list.getSelectedValue();
                            lp.load(new File("projects/" + Editor.getProjectName() + "/labels/"
                                    + list.getModel().getElementAt(index) + ".rbd"));
                        }
                    } catch (NullPointerException npe) {
                        lp.hide();
                        list.clearSelection();
                    }
                }
            }
        }
    });
    JScrollPane listPane = new JScrollPane(labelList);
    listPane.getVerticalScrollBar().setUnitIncrement(Editor.SCROLL_SPEED);
    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    this.add(buttons);
    this.add(listPane);

}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplateLibrariesPanel.java

private void initComponents(Channel channel) {
    setBackground(UIConstants.BACKGROUND_COLOR);

    selectAllLabel = new JLabel("<html><u>Select All</u></html>");
    selectAllLabel.setForeground(Color.BLUE);
    selectAllLabel.addMouseListener(new MouseAdapter() {
        @Override/*  w  ww.  ja  va  2  s.c o  m*/
        public void mouseReleased(MouseEvent evt) {
            for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((MutableTreeTableNode) libraryTreeTable
                    .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                MutableTreeTableNode libraryNode = libraryNodes.nextElement();
                Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNode
                        .getUserObject();
                libraryTreeTable.getTreeTableModel().setValueAt(
                        new MutableTriple<String, String, Boolean>(triple.getLeft(), triple.getMiddle(), true),
                        libraryNode, libraryTreeTable.getHierarchicalColumn());
            }
            libraryTreeTable.updateUI();
        }
    });

    selectSeparatorLabel = new JLabel("|");

    deselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    deselectAllLabel.setForeground(Color.BLUE);
    deselectAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((MutableTreeTableNode) libraryTreeTable
                    .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                MutableTreeTableNode libraryNode = libraryNodes.nextElement();
                Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNode
                        .getUserObject();
                libraryTreeTable.getTreeTableModel().setValueAt(
                        new MutableTriple<String, String, Boolean>(triple.getLeft(), triple.getMiddle(), false),
                        libraryNode, libraryTreeTable.getHierarchicalColumn());
            }
            libraryTreeTable.updateUI();
        }
    });

    expandAllLabel = new JLabel("<html><u>Expand All</u></html>");
    expandAllLabel.setForeground(Color.BLUE);
    expandAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            libraryTreeTable.expandAll();
        }
    });

    expandSeparatorLabel = new JLabel("|");

    collapseAllLabel = new JLabel("<html><u>Collapse All</u></html>");
    collapseAllLabel.setForeground(Color.BLUE);
    collapseAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            libraryTreeTable.collapseAll();
        }
    });

    final TableCellEditor libraryCellEditor = new LibraryTreeCellEditor();

    libraryTreeTable = new MirthTreeTable() {
        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return libraryCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

    DefaultTreeTableModel model = new SortableTreeTableModel();
    DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode();
    model.setRoot(rootNode);

    libraryTreeTable.setLargeModel(true);
    libraryTreeTable.setTreeTableModel(model);
    libraryTreeTable.setOpenIcon(null);
    libraryTreeTable.setClosedIcon(null);
    libraryTreeTable.setLeafIcon(null);
    libraryTreeTable.setRootVisible(false);
    libraryTreeTable.setDoubleBuffered(true);
    libraryTreeTable.setDragEnabled(false);
    libraryTreeTable.setRowSelectionAllowed(true);
    libraryTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    libraryTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    libraryTreeTable.setFocusable(true);
    libraryTreeTable.setOpaque(true);
    libraryTreeTable.setEditable(true);
    libraryTreeTable.setSortable(false);
    libraryTreeTable.setAutoCreateColumnsFromModel(false);
    libraryTreeTable.setShowGrid(true, true);
    libraryTreeTable.setTableHeader(null);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        libraryTreeTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    libraryTreeTable.setTreeCellRenderer(new LibraryTreeCellRenderer());

    libraryTreeTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelection(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelection(evt);
        }

        private void checkSelection(MouseEvent evt) {
            if (libraryTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())) < 0) {
                libraryTreeTable.clearSelection();
            }
        }
    });

    libraryTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting()) {
                boolean visible = false;
                int selectedRow = libraryTreeTable.getSelectedRow();

                if (selectedRow >= 0) {
                    TreePath selectedPath = libraryTreeTable.getPathForRow(selectedRow);
                    if (selectedPath != null) {
                        visible = true;
                        Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) ((MutableTreeTableNode) selectedPath
                                .getLastPathComponent()).getUserObject();
                        String description = "";

                        if (selectedPath.getPathCount() == 2) {
                            description = libraryMap.get(triple.getLeft()).getDescription();
                        } else if (selectedPath.getPathCount() == 3) {
                            description = PlatformUI.MIRTH_FRAME.codeTemplatePanel.getCachedCodeTemplates()
                                    .get(triple.getLeft()).getDescription();
                        }

                        if (StringUtils.isBlank(description) || StringUtils.equals(description, CodeTemplateUtil
                                .getDocumentation(CodeTemplate.DEFAULT_CODE).getDescription())) {
                            descriptionTextPane.setText(
                                    "<html><body class=\"code-template-libraries-panel\"><i>No description.</i></body></html>");
                        } else {
                            descriptionTextPane.setText("<html><body class=\"code-template-libraries-panel\">"
                                    + MirthXmlUtil.encode(description) + "</body></html>");
                        }
                    }
                }

                descriptionScrollPane.setVisible(visible);
                updateUI();
            }
        }
    });

    libraryTreeTableScrollPane = new JScrollPane(libraryTreeTable);

    descriptionTextPane = new JTextPane();
    descriptionTextPane.setContentType("text/html");
    HTMLEditorKit editorKit = new HTMLEditorKit();
    StyleSheet styleSheet = editorKit.getStyleSheet();
    styleSheet.addRule(".code-template-libraries-panel {font-family:\"Tahoma\";font-size:11;text-align:top}");
    descriptionTextPane.setEditorKit(editorKit);
    descriptionTextPane.setEditable(false);
    descriptionScrollPane = new JScrollPane(descriptionTextPane);
    descriptionScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    descriptionScrollPane.setVisible(false);
}

From source file:de.codesourcery.jasm16.ide.ui.views.WorkspaceExplorer.java

private JPanel createPanel() {
    treeModel = createTreeModel();//  w w w  .j  av  a2 s .co m
    tree.setModel(treeModel);
    setColors(tree);
    tree.setRootVisible(false);

    //      for (int i = 0; i < tree.getRowCount(); i++) {
    //         tree.expandRow(i);
    //      }

    tree.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                final WorkspaceTreeNode selection = getSelectedNode();
                if (selection != null) {
                    deleteResource(selection);
                }
            } else if (e.getKeyCode() == KeyEvent.VK_F5) {
                refreshWorkspace(null);
            }
        }
    });

    tree.addMouseListener(new MouseAdapter() {

        public void mouseClicked(java.awt.event.MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                final TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (path != null) {
                    final WorkspaceTreeNode selected = (WorkspaceTreeNode) path.getLastPathComponent();
                    final IAssemblyProject project = getProject(selected);
                    try {
                        if (project != null) {
                            onTreeNodeLeftClick(project, selected);
                        } else {
                            System.err.println("Unable to locate project for " + selected);
                        }
                    } catch (IOException e1) {
                        LOG.error("mouseClicked(): Internal error", e1);
                    }
                }
            }
        }
    });

    final TreeSelectionListener selectionListener = new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {

        }
    };

    tree.getSelectionModel().addTreeSelectionListener(selectionListener);

    tree.setCellRenderer(new DefaultTreeCellRenderer() {

        public Color getTextSelectionColor() {
            return Color.GREEN;
        };

        public java.awt.Color getTextNonSelectionColor() {
            return Color.GREEN;
        };

        public Color getBackgroundSelectionColor() {
            return Color.BLACK;
        };

        public Color getBackgroundNonSelectionColor() {
            return Color.BLACK;
        };

        public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {

            java.awt.Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
                    row, hasFocus);

            String label = value.toString();
            Color color = getTextColor();
            if (value instanceof WorkspaceTreeNode) {
                if (value instanceof ProjectNode) {
                    final ProjectNode projectNode = (ProjectNode) value;
                    final IAssemblyProject project = projectNode.getValue();
                    label = project.getName();

                    if (project.isClosed()) {
                        color = Color.LIGHT_GRAY;
                    } else {
                        if (projectNode.hasCompilationErrors()) {
                            color = Color.RED;
                        }
                    }
                } else if (value instanceof FileNode) {
                    FileNode fn = (FileNode) value;
                    label = fn.getValue().getName();
                    switch (fn.type) {
                    case DIRECTORY:
                        if (fn.hasCompilationErrors()) {
                            color = Color.RED;
                        }
                        break;
                    case OBJECT_FILE:
                        label = "[O] " + label;
                        break;
                    case EXECUTABLE:
                        label = "[E] " + label;
                        break;
                    case SOURCE_CODE:
                        label = "[S] " + label;
                        if (fn.hasCompilationErrors()) {
                            color = Color.RED;
                        }
                        break;
                    default:
                        // ok
                    }
                }
            }
            setForeground(color);
            setText(label);
            return result;
        };

    });

    setupPopupMenu();

    final JScrollPane pane = new JScrollPane(tree);
    setColors(pane);

    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());
    GridBagConstraints cnstrs = constraints(0, 0, true, true, GridBagConstraints.BOTH);
    setColors(result);
    result.add(pane, cnstrs);
    return result;
}