Example usage for javax.swing PopupFactory getSharedInstance

List of usage examples for javax.swing PopupFactory getSharedInstance

Introduction

In this page you can find the example usage for javax.swing PopupFactory getSharedInstance.

Prototype

public static PopupFactory getSharedInstance() 

Source Link

Document

Returns the shared PopupFactory which can be used to obtain Popups.

Usage

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

protected void showTooltip(JComponent field, String text) {
    if (!field.isShowing())
        return;//from  w w w.  jav  a 2  s  . com

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

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

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

    component = field;

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

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

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

    window = tooltipContainer;
    toolTipWindow = toolTip;

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

From source file: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 w  w  . j  av a 2 s  .com
    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:eu.crisis_economics.abm.dashboard.Page_Parameters.java

private Container initContainer() {
    JPanel containerPanel = new JPanel(new CardLayout());
    JLabel loadingModelLabel = new JLabel("Loading model...");
    loadingModelLabel.setHorizontalAlignment(SwingConstants.CENTER);
    containerPanel.add(loadingModelLabel, LOADING_MODEL_ID);
    tabbedPane = new JTabbedPane();
    containerPanel.add(tabbedPane, PARAMETERS_PANEL_ID);

    // create two number of turns field
    numberOfTurnsField = new JFormattedTextField();
    numberOfTurnsField.setFocusLostBehavior(JFormattedTextField.COMMIT);
    numberOfTurnsField.setInputVerifier(new InputVerifier() {

        @Override// ww w. j ava  2  s.c om
        public boolean verify(final JComponent input) {
            if (!checkNumberOfTurnsField(true)) {
                final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                final Point locationOnScreen = numberOfTurnsField.getLocationOnScreen();
                final JLabel message = new JLabel("Please specify a (possibly floating point) number!");
                message.setBorder(new LineBorder(Color.RED, 2, true));
                if (errorPopup != null)
                    errorPopup.hide();
                errorPopup = popupFactory.getPopup(numberOfTurnsField, message, locationOnScreen.x - 10,
                        locationOnScreen.y - 30);

                errorPopup.show();

                return false;
            } else {
                if (errorPopup != null) {
                    errorPopup.hide();
                    errorPopup = null;
                }
                return true;
            }
        }
    });
    numberOfTurnsField.setText(String.valueOf(Dashboard.NUMBER_OF_TURNS));
    numberOfTurnsField
            .setToolTipText("The turn when the simulation should stop specified as an integer value.");
    numberOfTurnsField.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            wizard.clickDefaultButton();
        }
    });

    numberOfTurnsFieldPSW = new JFormattedTextField();
    numberOfTurnsFieldPSW.setFocusLostBehavior(JFormattedTextField.COMMIT);
    numberOfTurnsFieldPSW.setInputVerifier(new InputVerifier() {

        @Override
        public boolean verify(final JComponent input) {
            if (!checkNumberOfTurnsField(false)) {
                final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                final Point locationOnScreen = numberOfTurnsFieldPSW.getLocationOnScreen();
                final JLabel message = new JLabel("Please specify a (possibly floating point) number!");
                message.setBorder(new LineBorder(Color.RED, 2, true));
                if (errorPopup != null)
                    errorPopup.hide();
                errorPopup = popupFactory.getPopup(numberOfTurnsFieldPSW, message, locationOnScreen.x - 10,
                        locationOnScreen.y - 30);

                errorPopup.show();

                return false;
            } else {
                if (errorPopup != null) {
                    errorPopup.hide();
                    errorPopup = null;
                }
                return true;
            }
        }
    });
    numberOfTurnsFieldPSW.setText(String.valueOf(Dashboard.NUMBER_OF_TURNS));
    numberOfTurnsFieldPSW
            .setToolTipText("The turn when the simulation should stop specified as an integer value.");
    numberOfTurnsFieldPSW.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            wizard.clickDefaultButton();
        }
    });

    // create two number of time-steps to ignore field
    numberTimestepsIgnored = new JFormattedTextField();
    numberTimestepsIgnored.setFocusLostBehavior(JFormattedTextField.COMMIT);
    numberTimestepsIgnored.setInputVerifier(new InputVerifier() {

        @Override
        public boolean verify(final JComponent input) {
            if (!checkNumberTimestepsIgnored(true)) {
                final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                final Point locationOnScreen = numberTimestepsIgnored.getLocationOnScreen();
                final JLabel message = new JLabel("Please specify an integer number!");
                message.setBorder(new LineBorder(Color.RED, 2, true));
                if (errorPopup != null)
                    errorPopup.hide();
                errorPopup = popupFactory.getPopup(numberTimestepsIgnored, message, locationOnScreen.x - 10,
                        locationOnScreen.y - 30);

                errorPopup.show();

                return false;
            } else {
                if (errorPopup != null) {
                    errorPopup.hide();
                    errorPopup = null;
                }
                return true;
            }
        }
    });
    numberTimestepsIgnored.setText(String.valueOf(Dashboard.NUMBER_OF_TIMESTEPS_TO_IGNORE));
    numberTimestepsIgnored.setToolTipText(
            "The turn when the simulation should start charting specified as an integer value.");
    numberTimestepsIgnored.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            wizard.clickDefaultButton();
        }
    });

    numberTimestepsIgnoredPSW = new JFormattedTextField();
    numberTimestepsIgnoredPSW.setFocusLostBehavior(JFormattedTextField.COMMIT);
    numberTimestepsIgnoredPSW.setInputVerifier(new InputVerifier() {

        @Override
        public boolean verify(final JComponent input) {
            if (!checkNumberTimestepsIgnored(false)) {
                final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                final Point locationOnScreen = numberTimestepsIgnoredPSW.getLocationOnScreen();
                final JLabel message = new JLabel("Please specify an integer number!");
                message.setBorder(new LineBorder(Color.RED, 2, true));
                if (errorPopup != null)
                    errorPopup.hide();
                errorPopup = popupFactory.getPopup(numberTimestepsIgnoredPSW, message, locationOnScreen.x - 10,
                        locationOnScreen.y - 30);

                errorPopup.show();

                return false;
            } else {
                if (errorPopup != null) {
                    errorPopup.hide();
                    errorPopup = null;
                }
                return true;
            }
        }
    });
    numberTimestepsIgnoredPSW.setText(String.valueOf(Dashboard.NUMBER_OF_TIMESTEPS_TO_IGNORE));
    numberTimestepsIgnoredPSW.setToolTipText(
            "The turn when the simulation should start charting specified as an integer value.");
    numberTimestepsIgnoredPSW.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(final ActionEvent e) {
            wizard.clickDefaultButton();
        }
    });

    onLineChartsCheckBox = new JCheckBox();
    //      onLineChartsCheckBoxPSW = new JCheckBox();
    advancedChartsCheckBox = new JCheckBox();
    advancedChartsCheckBox.setSelected(true);

    // create the scroll pane for the simple parameter setting page
    JLabel label = null;
    label = new JLabel(new ImageIcon(new ImageIcon(getClass().getResource(DECORATION_IMAGE)).getImage()
            .getScaledInstance(DECORATION_IMAGE_WIDTH, -1, Image.SCALE_SMOOTH)));
    Style.registerCssClasses(label, Dashboard.CSS_CLASS_COMMON_PANEL);
    parametersScrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    parametersScrollPane.setBorder(null);
    parametersScrollPane.setViewportBorder(null);

    breadcrumb = new Breadcrumb();
    Style.registerCssClasses(breadcrumb, CSS_ID_BREADCRUMB);

    singleRunParametersPanel = new ScrollableJPanel(new SizeProvider() {

        @Override
        public int getHeight() {
            Component component = tabbedPane.getSelectedComponent();
            if (component == null) {
                return 0;
            }
            JScrollBar scrollBar = parametersScrollPane.getHorizontalScrollBar();
            return component.getSize().height - breadcrumb.getHeight()
                    - (scrollBar.isVisible() ? scrollBar.getPreferredSize().height : 0);
        }

        @Override
        public int getWidth() {
            final int hScrollBarWidth = parametersScrollPane.getHorizontalScrollBar().getPreferredSize().width;
            final int width = dashboard.getSize().width - Page_Parameters.DECORATION_IMAGE_WIDTH
                    - hScrollBarWidth;
            return width;
        }
    });
    BoxLayout boxLayout = new BoxLayout(singleRunParametersPanel, BoxLayout.X_AXIS);
    singleRunParametersPanel.setLayout(boxLayout);
    parametersScrollPane.setViewportView(singleRunParametersPanel);

    JPanel breadcrumbPanel = new JPanel(new BorderLayout());
    breadcrumbPanel.add(breadcrumb, BorderLayout.NORTH);
    breadcrumbPanel.add(parametersScrollPane, BorderLayout.CENTER);

    final JPanel simpleForm = FormsUtils.build("p ~ p:g", "01 t:p", label, breadcrumbPanel).getPanel();
    Style.registerCssClasses(simpleForm, Dashboard.CSS_CLASS_COMMON_PANEL);

    tabbedPane.add("Single run", simpleForm);

    // create the form for the parameter sweep setting page
    tabbedPane.add("Parameter sweep", createParamsweepGUI());

    gaSearchHandler = new GASearchHandler(currentModelHandler);
    gaSearchPanel = new GASearchPanel(gaSearchHandler, this);
    tabbedPane.add("Genetic Algorithm Search", gaSearchPanel);

    return containerPanel;
}

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

protected void showNotificationPopup(String popupText, NotificationType type) {
    JPanel panel = new JPanel(new MigLayout("flowy"));
    panel.setBorder(BorderFactory.createLineBorder(Color.gray));

    switch (type) {
    case WARNING:
    case WARNING_HTML:
        panel.setBackground(Color.yellow);
        break;//from   ww w  . ja v a 2 s . c  om
    case ERROR:
    case ERROR_HTML:
        panel.setBackground(Color.orange);
        break;
    default:
        panel.setBackground(Color.cyan);
    }

    JLabel label = new JLabel(popupText);
    panel.add(label);

    Dimension labelSize = DesktopComponentsHelper.measureHtmlText(popupText);

    int x = frame.getX() + frame.getWidth() - (50 + labelSize.getSize().width);
    int y = frame.getY() + frame.getHeight() - (50 + labelSize.getSize().height);

    PopupFactory factory = PopupFactory.getSharedInstance();
    final Popup popup = factory.getPopup(frame, panel, x, y);
    popup.show();

    panel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            popup.hide();
        }
    });

    PointerInfo pointerInfo = MouseInfo.getPointerInfo();
    if (pointerInfo != null) {
        final Point location = pointerInfo.getLocation();
        final Timer timer = new Timer(3000, null);
        timer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                PointerInfo currentPointer = MouseInfo.getPointerInfo();
                if (currentPointer == null) {
                    timer.stop();
                } else if (!currentPointer.getLocation().equals(location)) {
                    popup.hide();
                    timer.stop();
                }
            }
        });
        timer.start();
    }
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private List<ParameterInfo> createAndDisplayAParameterPanel(
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title,
        final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify,
        final IModelHandler currentModelHandler) {
    final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(),
            unknownFields = new ArrayList<ParameterMetaData>();
    for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) {
        final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName);
        Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        while (true) {
            try {
                final Field field = modelComponentType.getDeclaredField(fieldName);
                final ParameterMetaData datum = new ParameterMetaData();
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                        continue;
                    final Class<? extends Annotation> type = element.annotationType();
                    datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element);
                    datum.banner = (String) type.getMethod("Title").invoke(element);
                    datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element);
                    datum.imageFileName = (String) type.getMethod("Image").invoke(element);
                    datum.layoutOrder = (Double) type.getMethod("Order").invoke(element);
                }//w  ww.j  a v a2s. co  m
                datum.parameter = record;
                if (datum.fieldName.trim().isEmpty())
                    datum.fieldName = parameterName.replaceAll("([A-Z])", " $1");
                metadata.add(datum);
                break;
            } catch (final SecurityException e) {
            } catch (final NoSuchFieldException e) {
            } catch (final IllegalArgumentException e) {
            } catch (final IllegalAccessException e) {
            } catch (final InvocationTargetException e) {
            } catch (final NoSuchMethodException e) {
            }
            modelComponentType = modelComponentType.getSuperclass();
            if (modelComponentType == null) {
                ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields);
                break;
            }
        }
    }
    Collections.sort(metadata);
    for (int i = unknownFields.size() - 1; i >= 0; --i)
        metadata.add(0, unknownFields.get(i));

    // initialize single run form
    final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", "");
    appendMinimumWidthHintToPresentation(formBuilder, 550);

    if (parent == null) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                numberOfTurnsField.grabFocus();
            }
        });

        appendBannerToPresentation(formBuilder, "General Parameters");
        appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation");

        formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField);
        formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored);

        appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox);
        appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT,
                advancedChartsCheckBox);
    }

    appendBannerToPresentation(formBuilder, title);

    final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree
            : findParameterInfoNode(parent, false);

    final List<ParameterInfo> info = new ArrayList<ParameterInfo>();

    // Search for a @ConfigurationComponent annotation
    {
        String headerText = "", imagePath = "";
        final Class<?> parentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        for (final Annotation element : parentType.getAnnotations()) { // Proxies
            if (element.annotationType().getName() != ConfigurationComponent.class.getName())
                continue;
            boolean doBreak = false;
            try {
                try {
                    headerText = (String) element.annotationType().getMethod("Description").invoke(element);
                    if (headerText.startsWith("#")) {
                        headerText = (String) parent.getActualType().getMethod(headerText.substring(1))
                                .invoke(parent.getInstance());
                    }
                    doBreak = true;
                } catch (IllegalArgumentException e) {
                } catch (SecurityException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } catch (final Exception e) {
            }
            try {
                imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element);
                doBreak = true;
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
            if (doBreak)
                break;
        }
        if (!headerText.isEmpty())
            appendHeaderTextToPresentation(formBuilder, headerText);
        if (!imagePath.isEmpty())
            appendImageToPresentation(formBuilder, imagePath);
    }

    if (metadata.isEmpty()) {
        // No fields to display.
        appendTextToPresentation(formBuilder, "No configuration is required for this module.");
    } else {
        for (final ParameterMetaData record : metadata) {
            final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter;

            if (!record.banner.isEmpty())
                appendBannerToPresentation(formBuilder, record.banner);
            if (!record.imageFileName.isEmpty())
                appendImageToPresentation(formBuilder, record.imageFileName);
            appendTextToPresentation(formBuilder, record.verboseDescription);

            final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo);
            if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) {
                //               sgi.setParentValue(parent.getActualType());
            }

            final JComponent field;
            final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true);
            Pair<ParameterInfo, JComponent> userData = null;
            JComponent oldField = null;
            if (oldNode != null) {
                userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject();
                oldField = userData.getSecond();
            }

            if (parameterInfo.isBoolean()) {
                field = new JCheckBox();
                boolean value = oldField != null ? ((JCheckBox) oldField).isSelected()
                        : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue();
                ((JCheckBox) field).setSelected(value);
            } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) {
                Object[] elements = null;
                if (parameterInfo.isEnum()) {
                    final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType();
                    elements = type.getEnumConstants();
                } else {
                    final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo;
                    elements = chooserInfo.getValidStrings();
                }
                final JComboBox list = new JComboBox(elements);

                if (parameterInfo.isEnum()) {
                    final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem()
                            : parameterInfo.getValue();
                    list.setSelectedItem(value);
                } else {
                    final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex()
                            : (Integer) parameterInfo.getValue();
                    list.setSelectedIndex(value);
                }

                field = list;
            } else if (parameterInfo instanceof SubmodelInfo) {
                final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                final Object[] elements = new Object[] { "Loading class information..." };
                final JComboBox list = new JComboBox(elements);
                //            field = list;

                final Object value = oldField != null
                        ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem()
                        : new ClassElement(submodelInfo.getActualType(), null);

                new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute();

                final JButton rightButton = new JButton();
                rightButton.setOpaque(false);
                rightButton.setRolloverEnabled(true);
                rightButton.setIcon(SHOW_SUBMODEL_ICON);
                rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO);
                rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS);
                rightButton.setBorder(null);
                rightButton.setToolTipText("Display submodel parameters");
                rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL);
                rightButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        if (parameterInfo instanceof SubmodelInfo) {
                            SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                            int level = 0;

                            showHideSubparameters(list, submodelInfo);

                            List<String> components = new ArrayList<String>();
                            components.add(submodelInfo.getName());
                            while (submodelInfo.getParent() != null) {
                                submodelInfo = submodelInfo.getParent();
                                components.add(submodelInfo.getName());
                                level++;
                            }
                            Collections.reverse(components);
                            final String[] breadcrumbText = components.toArray(new String[components.size()]);
                            for (int i = 0; i < breadcrumbText.length; ++i)
                                breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1");
                            breadcrumb.setPath(
                                    currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"),
                                    breadcrumbText);
                            Style.apply(breadcrumb, dashboard.getCssStyle());

                            // reset all buttons that are nested deeper than this to default color
                            for (int i = submodelButtons.size() - 1; i >= level; i--) {
                                JButton button = submodelButtons.get(i);
                                button.setIcon(SHOW_SUBMODEL_ICON);
                                submodelButtons.remove(i);
                            }

                            rightButton.setIcon(SHOW_SUBMODEL_ICON_RO);
                            submodelButtons.add(rightButton);
                        }
                    }
                });

                field = new JPanel(new BorderLayout());
                field.add(list, BorderLayout.CENTER);
                field.add(rightButton, BorderLayout.EAST);
            } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) {
                field = new JPanel(new BorderLayout());

                String oldName = "";
                String oldPath = "";
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldName = oldTextField.getText();
                    oldPath = oldTextField.getToolTipText();
                } else if (parameterInfo.getValue() != null) {
                    final File file = (File) parameterInfo.getValue();
                    oldName = file.getName();
                    oldPath = file.getAbsolutePath();
                }

                final JTextField textField = new JTextField(oldName);
                textField.setToolTipText(oldPath);
                textField.setInputVerifier(new InputVerifier() {

                    @Override
                    public boolean verify(final JComponent input) {
                        final JTextField inputField = (JTextField) input;
                        if (inputField.getText() == null || inputField.getText().isEmpty()) {
                            final File file = new File("");
                            inputField.setToolTipText(file.getAbsolutePath());
                            hideError();
                            return true;
                        }

                        final File oldFile = new File(inputField.getToolTipText());
                        if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) {
                            hideError();
                            return true;
                        }

                        inputField.setToolTipText("");
                        final File file = new File(inputField.getText().trim());
                        if (file.exists()) {
                            inputField.setToolTipText(file.getAbsolutePath());
                            inputField.setText(file.getName());
                            hideError();
                            return true;
                        } else {
                            final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                            final Point locationOnScreen = inputField.getLocationOnScreen();
                            final JLabel message = new JLabel("Please specify an existing file!");
                            message.setBorder(new LineBorder(Color.RED, 2, true));
                            if (errorPopup != null)
                                errorPopup.hide();
                            errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10,
                                    locationOnScreen.y - 30);
                            errorPopup.show();
                            return false;
                        }
                    }
                });

                final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT);
                browseButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JFileChooser fileDialog = new JFileChooser(
                                !"".equals(textField.getToolTipText()) ? textField.getToolTipText()
                                        : currentDirectory);
                        if (!"".equals(textField.getToolTipText()))
                            fileDialog.setSelectedFile(new File(textField.getToolTipText()));
                        int dialogResult = fileDialog.showOpenDialog(dashboard);
                        if (dialogResult == JFileChooser.APPROVE_OPTION) {
                            final File selectedFile = fileDialog.getSelectedFile();
                            if (selectedFile != null) {
                                currentDirectory = selectedFile.getAbsoluteFile().getParent();
                                textField.setText(selectedFile.getName());
                                textField.setToolTipText(selectedFile.getAbsolutePath());
                            }
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(browseButton, BorderLayout.EAST);
            } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo;

                field = new JPanel(new BorderLayout());

                String oldValueStr = String.valueOf(parameterInfo.getValue());
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldValueStr = oldTextField.getText();
                }

                final JTextField textField = new JTextField(oldValueStr);

                PercentJSlider tempSlider = null;
                if (intervalInfo.isDoubleInterval())
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(),
                            intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr));
                else
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(),
                            intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr));

                final PercentJSlider slider = tempSlider;
                slider.setMajorTickSpacing(100);
                slider.setMinorTickSpacing(10);
                slider.setPaintTicks(true);
                slider.setPaintLabels(true);
                slider.addChangeListener(new ChangeListener() {
                    public void stateChanged(final ChangeEvent _) {
                        if (slider.hasFocus()) {
                            final String value = intervalInfo.isDoubleInterval()
                                    ? String.valueOf(slider.getDoubleValue())
                                    : String.valueOf(slider.getLongValue());
                            textField.setText(value);
                            slider.setToolTipText(value);
                        }
                    }
                });

                textField.setInputVerifier(new InputVerifier() {
                    public boolean verify(JComponent input) {
                        final JTextField inputField = (JTextField) input;

                        try {
                            hideError();
                            final String valueStr = inputField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else
                                    showError(
                                            "Please specify a value between " + intervalInfo.getIntervalMin()
                                                    + " and " + intervalInfo.getIntervalMax() + ".",
                                            inputField);
                                return false;
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else {
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", inputField);
                                    return false;
                                }
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, inputField);
                            return false;
                        }

                    }
                });

                textField.getDocument().addDocumentListener(new DocumentListener() {
                    //               private Popup errorPopup;

                    public void removeUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void insertUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void changedUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    private void textFieldChanged() {
                        if (!textField.hasFocus()) {
                            hideError();
                            return;
                        }

                        try {
                            hideError();
                            final String valueStr = textField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify a value between " + intervalInfo.getIntervalMin()
                                            + " and " + intervalInfo.getIntervalMax() + ".", textField);
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", textField);
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, textField);
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(slider, BorderLayout.SOUTH);
            } else {
                final Object value = oldField != null ? ((JTextField) oldField).getText()
                        : parameterInfo.getValue();
                field = new JTextField(value.toString());
                ((JTextField) field).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        wizard.clickDefaultButton();
                    }
                });
            }

            final JLabel parameterLabel = new JLabel(record.fieldName);

            final String description = parameterInfo.getDescription();
            if (description != null && !description.isEmpty()) {
                parameterLabel.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance();

                        final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel,
                                description, dashboard.getCssStyle());

                        parameterDescriptionPopup.show();
                    }

                });
            }

            if (oldNode != null)
                userData.setSecond(field);
            else {
                final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo,
                        field);
                final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair);
                parentNode.add(newNode);
            }

            if (field instanceof JCheckBox) {
                parameterLabel
                        .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">"
                                + parameterLabel.getText() + "</div></html>");
                formBuilder.append(parameterLabel, field);

                //            appendCheckBoxFieldToPresentation(
                //               formBuilder, parameterLabel.getText(), (JCheckBox) field);
            } else {
                formBuilder.append(parameterLabel, field);
                final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel);
                constraints.vAlign = CellConstraints.TOP;
                constraints.insets = new Insets(5, 0, 0, 0);
                formBuilder.getLayout().setConstraints(parameterLabel, constraints);
            }

            // prepare the parameterInfo for the param sweeps
            parameterInfo.setRuns(0);
            parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF);
            parameterInfo.setValue(batchParameterInfo.getDefaultValue());
            info.add(parameterInfo);
        }
    }
    appendVerticalSpaceToPresentation(formBuilder);

    final JPanel panel = formBuilder.getPanel();
    singleRunParametersPanel.add(panel);

    if (singleRunParametersPanel.getComponentCount() > 1) {
        panel.setBorder(
                BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
                        BorderFactory.createEmptyBorder(0, 5, 0, 5)));
    } else {
        panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    }

    Style.apply(panel, dashboard.getCssStyle());

    return info;
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

private void showError(final String message, final JTextField textField) {
    PopupFactory popupFactory = PopupFactory.getSharedInstance();
    Point locationOnScreen = textField.getLocationOnScreen();
    JLabel messageLabel = new JLabel(message);
    messageLabel.setBorder(new LineBorder(Color.RED, 2, true));
    errorPopup = popupFactory.getPopup(textField, messageLabel, locationOnScreen.x - 10,
            locationOnScreen.y - 30);//w  w  w.  ja v a 2  s.com
    errorPopup.show();
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private void showNodeDataPopup(final MouseEvent e, final PhylogenyNode node) {
    try {/*from  w w  w  .j  av  a  2 s .  c o m*/
        if ((node.getNodeName().length() > 0)
                || (node.getNodeData().isHasTaxonomy() && !isTaxonomyEmpty(node.getNodeData().getTaxonomy()))
                || (node.getNodeData().isHasSequence() && !isSequenceEmpty(node.getNodeData().getSequence()))
                || (node.getNodeData().isHasDate()) || (node.getNodeData().isHasDistribution())
                || node.getBranchData().isHasConfidences()) {
            _popup_buffer.setLength(0);
            short lines = 0;
            if (node.getNodeName().length() > 0) {
                lines++;
                _popup_buffer.append(node.getNodeName());
            }
            if (node.getNodeData().isHasTaxonomy() && !isTaxonomyEmpty(node.getNodeData().getTaxonomy())) {
                lines++;
                boolean enc_data = false;
                final Taxonomy tax = node.getNodeData().getTaxonomy();
                if (_popup_buffer.length() > 0) {
                    _popup_buffer.append("\n");
                }
                if (!ForesterUtil.isEmpty(tax.getTaxonomyCode())) {
                    _popup_buffer.append("[");
                    _popup_buffer.append(tax.getTaxonomyCode());
                    _popup_buffer.append("]");
                    enc_data = true;
                }
                if (!ForesterUtil.isEmpty(tax.getScientificName())) {
                    if (enc_data) {
                        _popup_buffer.append(" ");
                    }
                    _popup_buffer.append(tax.getScientificName());
                    enc_data = true;
                }
                if (!ForesterUtil.isEmpty(tax.getCommonName())) {
                    if (enc_data) {
                        _popup_buffer.append(" (");
                    } else {
                        _popup_buffer.append("(");
                    }
                    _popup_buffer.append(tax.getCommonName());
                    _popup_buffer.append(")");
                    enc_data = true;
                }
                if (!ForesterUtil.isEmpty(tax.getAuthority())) {
                    if (enc_data) {
                        _popup_buffer.append(" (");
                    } else {
                        _popup_buffer.append("(");
                    }
                    _popup_buffer.append(tax.getAuthority());
                    _popup_buffer.append(")");
                    enc_data = true;
                }
                if (!ForesterUtil.isEmpty(tax.getRank())) {
                    if (enc_data) {
                        _popup_buffer.append(" [");
                    } else {
                        _popup_buffer.append("[");
                    }
                    _popup_buffer.append(tax.getRank());
                    _popup_buffer.append("]");
                    enc_data = true;
                }
                if (tax.getSynonyms().size() > 0) {
                    if (enc_data) {
                        _popup_buffer.append(" ");
                    }
                    _popup_buffer.append("[");
                    int counter = 1;
                    for (final String syn : tax.getSynonyms()) {
                        if (!ForesterUtil.isEmpty(syn)) {
                            _popup_buffer.append(syn);
                            if (counter < tax.getSynonyms().size()) {
                                _popup_buffer.append(", ");
                            }
                        }
                        counter++;
                    }
                    _popup_buffer.append("]");
                }
            }
            if (node.getNodeData().isHasSequence() && !isSequenceEmpty(node.getNodeData().getSequence())) {
                lines++;
                boolean enc_data = false;
                if (_popup_buffer.length() > 0) {
                    _popup_buffer.append("\n");
                }
                final Sequence seq = node.getNodeData().getSequence();
                if (seq.getAccession() != null) {
                    _popup_buffer.append("[");
                    if (!ForesterUtil.isEmpty(seq.getAccession().getSource())) {
                        _popup_buffer.append(seq.getAccession().getSource());
                        _popup_buffer.append("=");
                    }
                    _popup_buffer.append(seq.getAccession().getValue());
                    _popup_buffer.append("]");
                    enc_data = true;
                }
                if (!ForesterUtil.isEmpty(seq.getSymbol())) {
                    if (enc_data) {
                        _popup_buffer.append(" [");
                    } else {
                        _popup_buffer.append("[");
                    }
                    _popup_buffer.append(seq.getSymbol());
                    _popup_buffer.append("]");
                    enc_data = true;
                }
                if (!ForesterUtil.isEmpty(seq.getName())) {
                    if (enc_data) {
                        _popup_buffer.append(" ");
                    }
                    _popup_buffer.append(seq.getName());
                }
            }
            if (node.getNodeData().isHasDate()) {
                lines++;
                if (_popup_buffer.length() > 0) {
                    _popup_buffer.append("\n");
                }
                _popup_buffer.append(node.getNodeData().getDate().asSimpleText());
            }
            if (node.getNodeData().isHasDistribution()) {
                lines++;
                if (_popup_buffer.length() > 0) {
                    _popup_buffer.append("\n");
                }
                _popup_buffer.append(node.getNodeData().getDistribution().asSimpleText());
            }
            if (node.getBranchData().isHasConfidences()) {
                final List<Confidence> confs = node.getBranchData().getConfidences();
                for (final Confidence confidence : confs) {
                    lines++;
                    if (_popup_buffer.length() > 0) {
                        _popup_buffer.append("\n");
                    }
                    if (!ForesterUtil.isEmpty(confidence.getType())) {
                        _popup_buffer.append("[");
                        _popup_buffer.append(confidence.getType());
                        _popup_buffer.append("] ");
                    } else {
                        _popup_buffer.append("[?] ");
                    }
                    _popup_buffer.append(FORMATTER_CONFIDENCE.format(ForesterUtil.round(confidence.getValue(),
                            getOptions().getNumberOfDigitsAfterCommaForConfidenceValues())));
                }
            }
            if (_popup_buffer.length() > 0) {
                if (!getConfiguration().isUseNativeUI()) {
                    _rollover_popup
                            .setBorder(BorderFactory.createLineBorder(getTreeColorSet().getBranchColor()));
                    _rollover_popup.setBackground(getTreeColorSet().getBackgroundColor());
                    if (isInFoundNodes(node)) {
                        _rollover_popup.setForeground(getTreeColorSet().getFoundColor());
                    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
                        _rollover_popup.setForeground(getTaxonomyBasedColor(node));
                    } else {
                        _rollover_popup.setForeground(getTreeColorSet().getSequenceColor());
                    }
                } else {
                    _rollover_popup.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                }
                _rollover_popup.setText(_popup_buffer.toString());
                //_rollover_popup.setText("Hallo");
                _node_desc_popup = PopupFactory.getSharedInstance().getPopup(null, _rollover_popup,
                        e.getLocationOnScreen().x + 10, e.getLocationOnScreen().y - (lines * 20));
                _node_desc_popup.show();
            }
        }
    } catch (final Exception ex) {
        // Do nothing.
    }
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private void showBranchDataPopup(final MouseEvent e, final PhylogenyNode node) {
    try {/*  ww w. ja  va2  s.  c o  m*/
        String[] histdata = null;
        short lines = 10;
        // show inserted species on branch
        if (!(((Annotation) node.getNodeData().getSequences().get(0).getAnnotation(0)).getDesc()
                .length() < 10)) { // as long as there are no branch names longer than 9 characters, this is going to work
            lines++;
            _popup_buffer.delete(0, _popup_buffer.length());
            histdata = ((Annotation) node.getNodeData().getSequences().get(0).getAnnotation(0)).getDesc()
                    .split(",");
            _popup_buffer
                    .append("RAxml Weights Histogram " + node.getNodeData().getSequence(0).getName() + "\n");

            String branch_data = "";
            // parse the histogram
            Pattern p = Pattern.compile("\\s*\\d\\.\\d\\s-\\s\\d\\.\\d:\\s[\\|\\.]*\\s*\\d+");
            for (int i = 0; i < histdata.length; i++) {

                //##################################
                // Parse Node Description a[i] here!

                Matcher m = p.matcher(histdata[i]);
                if (m.matches()) {
                    branch_data = branch_data + histdata[i] + "\n";

                    //   System.out.println(a[i]);
                }

            }
            _popup_buffer.append(branch_data);

            //_popup_buffer.append(((Annotation)node.getNodeData().getSequence().getAnnotation(0)).getDesc());     
        } else if (node.getNodeData().isHasSequence()) {
            _popup_buffer.delete(0, _popup_buffer.length());
            _popup_buffer.append(node.getNodeData().getSequence(0).getName());
        }

        if (_popup_buffer.length() > 0) {
            if (!getConfiguration().isUseNativeUI()) {
                _rollover_popup.setBorder(BorderFactory.createLineBorder(getTreeColorSet().getBranchColor()));
                _rollover_popup.setBackground(getTreeColorSet().getBackgroundColor());
                if (isInFoundNodes(node)) {
                    _rollover_popup.setForeground(getTreeColorSet().getFoundColor());
                } else if (getControlPanel().isColorAccordingToTaxonomy()) {
                    _rollover_popup.setForeground(getTaxonomyBasedColor(node));
                } else {
                    _rollover_popup.setForeground(getTreeColorSet().getSequenceColor());
                }
            } else {
                _rollover_popup.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            }

            CategoryDataset data = createDataset(histdata);
            JFreeChart histogram = createChart(data, node.getNodeData().getSequence(0).getName());
            _chart_panel = new ChartPanel(histogram, 300, 200, ChartPanel.DEFAULT_MINIMUM_DRAW_WIDTH,
                    ChartPanel.DEFAULT_MINIMUM_DRAW_HEIGHT, ChartPanel.DEFAULT_MAXIMUM_DRAW_WIDTH,
                    ChartPanel.DEFAULT_MAXIMUM_DRAW_HEIGHT, ChartPanel.DEFAULT_BUFFER_USED, false, false, false,
                    false, true);
            _rollover_popup.setText(_popup_buffer.toString());//_popup_buffer.toString() );
            _node_desc_popup = PopupFactory.getSharedInstance().getPopup(null, _chart_panel,
                    e.getLocationOnScreen().x + 10, e.getLocationOnScreen().y - (10));
            _node_desc_popup.show();
        }
    } catch (final Exception ex) {
        // Do nothing.
    }
}