Example usage for javax.swing BorderFactory createMatteBorder

List of usage examples for javax.swing BorderFactory createMatteBorder

Introduction

In this page you can find the example usage for javax.swing BorderFactory createMatteBorder.

Prototype

public static MatteBorder createMatteBorder(int top, int left, int bottom, int right, Icon tileIcon) 

Source Link

Document

Creates a matte-look border that consists of multiple tiles of a specified icon.

Usage

From source file:net.sf.jabref.gui.groups.GroupSelector.java

private void setEditMode(boolean editMode) {
    Globals.prefs.putBoolean(JabRefPreferences.EDIT_GROUP_MEMBERSHIP_MODE, editModeIndicator);
    editModeIndicator = editMode;/*from  w ww  . ja  v  a  2 s  . c o  m*/

    if (editMode) {
        groupsTree.setBorder(
                BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.RED),
                        "Edit mode", TitledBorder.RIGHT, TitledBorder.TOP, Font.getFont("Default"), Color.RED));
        this.setTitle("<html><font color='red'>Groups Edit mode</font></html>");
    } else {
        groupsTree.setBorder(BorderFactory.createEmptyBorder(5, 10, 0, 0));
        this.setTitle(Localization.lang("Groups"));
    }
    groupsTree.revalidate();
    groupsTree.repaint();
}

From source file:com.mirth.connect.client.ui.panels.connectors.PollingSettingsPanel.java

private void initLayout() {
    setBackground(UIConstants.BACKGROUND_COLOR);

    if (channelContext) {
        setLayout(new MigLayout("novisualpadding, hidemode 3, insets 0, gap 6 4", "[]12[]"));
        setBorder(javax.swing.BorderFactory.createTitledBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(204, 204, 204)), "Polling Settings",
                TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Tahoma", 1, 11)));

        add(scheduleTypeLabel, "right");
        add(scheduleTypeComboBox, "split");
        add(nextPollLabel, "gapbefore 6");

        add(new JLabel("Poll Once on Start:"), "newline, right");
        add(yesStartPollRadioButton, "split");
        add(noStartPollRadioButton, "gapbefore 5");
    } else {/*from  w  w  w .  j  av  a  2s  . co m*/
        setLayout(new MigLayout("novisualpadding, hidemode 3, insets 0, gap 6 6", "[]12[]"));
        add(scheduleTypeLabel, "right");
        add(scheduleTypeComboBox);
    }

    add(timeSettingsLabel, "newline, right");
    scheduleSettingsPanel.setLayout(new MigLayout("novisualpadding, hidemode 3, insets 0, gap 6 6"));

    scheduleSettingsPanel.add(pollingTimePicker, "w 70!");

    pollingFrequencySettingsPanel.setLayout(new MigLayout("novisualpadding, insets 0, gap 6 6"));
    pollingFrequencySettingsPanel.add(pollingFrequencyField, "w 75!, left");
    pollingFrequencySettingsPanel.add(pollingFrequencyTypeComboBox, "left");
    scheduleSettingsPanel.add(pollingFrequencySettingsPanel);

    pollingCronSettingsPanel.setLayout(new MigLayout("novisualpadding, insets 0, gap 6 6"));
    pollingCronSettingsPanel.add(cronScrollPane, "h 74!, w 400!");

    JPanel buttonPanel = new JPanel(new MigLayout("novisualpadding, insets 0, gap 6 6"));
    buttonPanel.setBackground(UIConstants.BACKGROUND_COLOR);
    buttonPanel.add(addJobButton, "wrap, w 50!");
    buttonPanel.add(deleteJobButton, "w 50!");
    pollingCronSettingsPanel.add(buttonPanel, "top");
    scheduleSettingsPanel.add(pollingCronSettingsPanel);

    add(scheduleSettingsPanel, "split");
    add(advancedSettingsButton, "gapbefore 6, h 21!, w 22!");
}

From source file:edu.ku.brc.af.ui.forms.ViewFactory.java

/**
 * Makes adjusts to the border and the colors to make it "flat" for display mode.
 * @param textField the text field to be flattened
 * @param isTransparent make the background transparent instead of using the viewFieldColor
 *///from w  w  w . j a  v  a2 s.c  o m
public static void changeTextFieldUIForDisplay(final JTextField textField, final Color borderColor,
        final boolean isTransparent) {
    Insets insets = textField.getBorder().getBorderInsets(textField);
    if (borderColor != null) {
        textField.setBorder(BorderFactory.createMatteBorder(Math.min(insets.top, 3), Math.min(insets.left, 3),
                Math.min(insets.bottom, 3), Math.min(insets.right, 3), borderColor));
    } else {
        textField.setBorder(BorderFactory.createEmptyBorder(Math.min(insets.top, 3), Math.min(insets.left, 3),
                Math.min(insets.bottom, 3), Math.min(insets.right, 3)));
    }
    textField.setForeground(Color.BLACK);
    textField.setEditable(false);
    //textField.setFocusable(false); // rods - commented out because it makes it so you can't select and copy

    textField.setOpaque(!isTransparent);
    if (isTransparent) {
        textField.setBackground(null);

    } else if (viewFieldColor != null) {
        textField.setBackground(viewFieldColor.getColor());
    }
}

From source file:com.mirth.connect.client.ui.DashboardPanel.java

private void initComponents() {
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    splitPane.setOneTouchExpandable(true);

    topPanel = new JPanel();
    topPanel.setBackground(UIConstants.BACKGROUND_COLOR);

    dashboardTable = null;/*  w  w w .  jav a 2 s  .com*/
    dashboardTableScrollPane = new JScrollPane();
    dashboardTableScrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    dashboardTableScrollPane.setViewportView(dashboardTable);
    dashboardTableScrollPane.setDoubleBuffered(true);

    controlPanel = new JPanel();
    controlPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(164, 164, 164)));
    controlPanel.setPreferredSize(new Dimension(100, 20));

    tagFilterButton = new IconButton();
    tagFilterButton
            .setIcon(new ImageIcon(getClass().getResource("/com/mirth/connect/client/ui/images/wrench.png"))); // NOI18N
    tagFilterButton.setToolTipText("Show Channel Filter");
    tagFilterButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            tagFilterButtonActionPerformed();
        }
    });

    tagsLabel = new JLabel();

    ButtonGroup showStatsButtonGroup = new ButtonGroup();

    showCurrentStatsButton = new JRadioButton("Current Statistics");
    showCurrentStatsButton.setSelected(true);
    showCurrentStatsButton
            .setToolTipText("Show the statistics accumulated since the last time the statistics were reset");
    showCurrentStatsButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            showCurrentStatsButtonActionPerformed();
        }
    });
    showStatsButtonGroup.add(showCurrentStatsButton);

    showLifetimeStatsButton = new JRadioButton("Lifetime Statistics");
    showLifetimeStatsButton
            .setToolTipText("Show the statistics accumulated over the entire lifetime of the channel");
    showLifetimeStatsButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            showLifetimeStatsButtonActionPerformed();
        }
    });
    showStatsButtonGroup.add(showLifetimeStatsButton);

    pluginContainerPanel = new JPanel();

    controlSeparator = new JSeparator(SwingConstants.VERTICAL);

    ButtonGroup tableModeButtonGroup = new ButtonGroup();

    tableModeGroupsButton = new IconToggleButton(UIConstants.ICON_GROUP);
    tableModeGroupsButton.setToolTipText("Groups");
    tableModeGroupsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            switchTableMode(true);
        }
    });
    tableModeButtonGroup.add(tableModeGroupsButton);

    tableModeChannelsButton = new IconToggleButton(UIConstants.ICON_CHANNEL);
    tableModeChannelsButton.setToolTipText("Channels");
    tableModeChannelsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            switchTableMode(false);
        }
    });
    tableModeButtonGroup.add(tableModeChannelsButton);

    tabPane = new JTabbedPane();

    splitPane.setTopComponent(topPanel);
    splitPane.setBottomComponent(tabPane);
}

From source file:de.bwravencl.controllerbuddy.gui.Main.java

private void onControllersChanged(final boolean selectFirstTab) {
    final var presentJids = new HashSet<Integer>();
    for (var jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++)
        if (glfwJoystickPresent(jid) && glfwJoystickIsGamepad(jid)) {
            presentJids.add(jid);/*from   www . j ava 2 s  .  c om*/

            if (!isSelectedJidValid())
                setSelectedJid(jid);
        }

    final var controllerConnected = !presentJids.isEmpty();
    if (!controllerConnected)
        selectedJid = INVALID_JID;

    final var previousSelectedTabIndex = tabbedPane.getSelectedIndex();
    fileMenu.remove(newMenuItem);
    fileMenu.remove(openMenuItem);
    fileMenu.remove(saveMenuItem);
    fileMenu.remove(saveAsMenuItem);
    if (fileMenu.getItemCount() > 1)
        fileMenu.remove(0);
    deviceMenu.removeAll();
    menuBar.remove(deviceMenu);
    menuBar.remove(localMenu);
    menuBar.remove(serverMenu);
    tabbedPane.remove(modesPanel);
    tabbedPane.remove(assignmentsComponent);
    tabbedPane.remove(overlayPanel);

    if (controllerConnected) {
        fileMenu.insert(newMenuItem, 0);
        fileMenu.insert(openMenuItem, 1);
        fileMenu.insert(saveMenuItem, 2);
        fileMenu.insert(saveAsMenuItem, 3);
        fileMenu.insertSeparator(4);

        for (final var jid : presentJids)
            deviceMenu.add(new SelectControllerAction(jid));
        menuBar.add(deviceMenu, 1);

        if (windows)
            menuBar.add(localMenu, 2);

        menuBar.add(serverMenu, windows ? 4 : 2);

        modesPanel = new JPanel(new BorderLayout());
        tabbedPane.insertTab(rb.getString("MODES_TAB"), null, modesPanel, null,
                tabbedPane.indexOfComponent(settingsScrollPane));

        modesListPanel = new JPanel();
        modesListPanel.setLayout(new GridBagLayout());

        modesScrollPane = new JScrollPane();
        modesScrollPane.setViewportBorder(
                BorderFactory.createMatteBorder(10, 10, 0, 10, modesListPanel.getBackground()));
        modesPanel.add(modesScrollPane, BorderLayout.CENTER);

        addModePanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        final var addButton = new JButton(new AddModeAction());
        addButton.setPreferredSize(BUTTON_DIMENSION);
        addModePanel.add(addButton);
        modesPanel.add(addModePanel, BorderLayout.SOUTH);

        assignmentsComponent = new AssignmentsComponent(this);
        tabbedPane.insertTab(rb.getString("ASSIGNMENTS_TAB"), null, assignmentsComponent, null,
                tabbedPane.indexOfComponent(settingsScrollPane));

        overlayPanel = new JPanel(new BorderLayout());

        indicatorsListPanel = new JPanel();
        indicatorsListPanel.setLayout(new GridBagLayout());

        indicatorsScrollPane = new JScrollPane();
        indicatorsScrollPane.setViewportBorder(
                BorderFactory.createMatteBorder(10, 10, 0, 10, indicatorsListPanel.getBackground()));
        overlayPanel.add(indicatorsScrollPane, BorderLayout.CENTER);
        tabbedPane.insertTab(rb.getString("OVERLAY_TAB"), null, overlayPanel, null,
                tabbedPane.indexOfComponent(settingsScrollPane));
    }

    if (selectFirstTab || !controllerConnected)
        tabbedPane.setSelectedIndex(0);
    else if (previousSelectedTabIndex < tabbedPane.getTabCount())
        tabbedPane.setSelectedIndex(previousSelectedTabIndex);

    updateModesPanel();
    updateOverlayPanel();
    updatePanelAccess();

    frame.getContentPane().invalidate();
    frame.getContentPane().repaint();
}

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

private void initComponents() {
    splitPane = new JSplitPane();
    splitPane.setBackground(getBackground());
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder());
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(/*from  w ww .j  av a  2  s .  com*/
            Preferences.userNodeForPackage(Mirth.class).getInt("height", UIConstants.MIRTH_HEIGHT) / 3);
    splitPane.setResizeWeight(0.5);

    topPanel = new JPanel();
    topPanel.setBackground(UIConstants.COMBO_BOX_BACKGROUND);

    final CodeTemplateTreeTableCellEditor templateCellEditor = new CodeTemplateTreeTableCellEditor(this);

    templateTreeTable = new MirthTreeTable("CodeTemplate", new HashSet<String>(
            Arrays.asList(new String[] { "Name", "Description", "Revision", "Last Modified" }))) {

        private TreeTableNode selectedNode;

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == TEMPLATE_NAME_COLUMN;
        }

        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return templateCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }

        @Override
        protected void beforeSort() {
            updateCurrentNode();
            updateCurrentNode.set(false);

            int selectedRow = templateTreeTable.getSelectedRow();
            selectedNode = selectedRow >= 0
                    ? (TreeTableNode) templateTreeTable.getPathForRow(selectedRow).getLastPathComponent()
                    : null;
        }

        @Override
        protected void afterSort() {
            final TreePath selectedPath = selectPathFromNodeId(selectedNode,
                    (CodeTemplateRootTreeTableNode) templateTreeTable.getTreeTableModel().getRoot());
            if (selectedPath != null) {
                selectTemplatePath(selectedPath);
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (selectedPath != null) {
                        selectTemplatePath(selectedPath);
                    }
                    updateCurrentNode.set(true);
                }
            });
        }
    };

    DefaultTreeTableModel model = new CodeTemplateTreeTableModel();
    model.setColumnIdentifiers(
            Arrays.asList(new String[] { "Name", "Id", "Type", "Description", "Revision", "Last Modified" }));

    CodeTemplateRootTreeTableNode rootNode = new CodeTemplateRootTreeTableNode();
    model.setRoot(rootNode);

    fullModel = new CodeTemplateTreeTableModel();
    fullModel.setColumnIdentifiers(
            Arrays.asList(new String[] { "Name", "Id", "Type", "Description", "Revision", "Last Modified" }));

    CodeTemplateRootTreeTableNode fullRootNode = new CodeTemplateRootTreeTableNode();
    fullModel.setRoot(fullRootNode);

    templateTreeTable.setColumnFactory(new CodeTemplateTableColumnFactory());
    templateTreeTable.setTreeTableModel(model);
    templateTreeTable.setOpenIcon(null);
    templateTreeTable.setClosedIcon(null);
    templateTreeTable.setLeafIcon(null);
    templateTreeTable.setRootVisible(false);
    templateTreeTable.setDoubleBuffered(true);
    templateTreeTable.setDragEnabled(false);
    templateTreeTable.setRowSelectionAllowed(true);
    templateTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    templateTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    templateTreeTable.setFocusable(true);
    templateTreeTable.setOpaque(true);
    templateTreeTable.getTableHeader().setReorderingAllowed(true);
    templateTreeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    templateTreeTable.setEditable(true);
    templateTreeTable.setSortable(true);
    templateTreeTable.setAutoCreateColumnsFromModel(false);
    templateTreeTable.setShowGrid(true, true);
    templateTreeTable.restoreColumnPreferences();
    templateTreeTable.setMirthColumnControlEnabled(true);

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

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

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

        private void checkSelection(MouseEvent evt) {
            int row = templateTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY()));

            if (row < 0) {
                templateTreeTable.clearSelection();
            }

            if (evt.isPopupTrigger()) {
                if (row != -1) {
                    if (!templateTreeTable.isRowSelected(row)) {
                        templateTreeTable.setRowSelectionInterval(row, row);
                    }
                }
                codeTemplatePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
        }
    });

    templateTreeTable.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                TreePath selectedPath = templateTreeTable.getTreeSelectionModel().getSelectionPath();
                if (selectedPath != null) {
                    MutableTreeTableNode selectedNode = (MutableTreeTableNode) selectedPath
                            .getLastPathComponent();
                    if (selectedNode instanceof CodeTemplateLibraryTreeTableNode && codeTemplateTasks
                            .getContentPane().getComponent(TASK_CODE_TEMPLATE_LIBRARY_DELETE).isVisible()) {
                        doDeleteLibrary();
                    } else if (selectedNode instanceof CodeTemplateTreeTableNode && codeTemplateTasks
                            .getContentPane().getComponent(TASK_CODE_TEMPLATE_DELETE).isVisible()) {
                        doDeleteCodeTemplate();
                    }
                }
            }
        }
    });

    templateTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting() && !templateTreeTable.getSelectionModel().getValueIsAdjusting()) {
                int selectedRow = templateTreeTable.getSelectedRow();

                boolean saveEnabled = isSaveEnabled();
                boolean adjusting = saveAdjusting.getAndSet(true);

                printTreeTable();

                updateCurrentNode();
                currentSelectedRow = selectedRow;

                if (selectedRow < 0) {
                    if (!adjusting) {
                        switchSplitPaneComponent(blankPanel);
                    }
                } else {
                    TreePath path = templateTreeTable.getPathForRow(selectedRow);
                    if (path != null) {
                        TreeTableNode node = (TreeTableNode) path.getLastPathComponent();

                        if (node instanceof CodeTemplateLibraryTreeTableNode) {
                            setLibraryProperties((CodeTemplateLibraryTreeTableNode) node);
                            switchSplitPaneComponent(libraryPanel);
                        } else if (node instanceof CodeTemplateTreeTableNode) {
                            setCodeTemplateProperties((CodeTemplateTreeTableNode) node);
                            switchSplitPaneComponent(templatePanel);
                        }
                    }
                }

                updateTasks();

                setSaveEnabled(saveEnabled);
                if (!adjusting) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            saveAdjusting.set(false);
                        }
                    });
                }
            }
        }
    });

    templateTreeTable.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            treeExpansionChanged();
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
            treeExpansionChanged();
        }

        private void treeExpansionChanged() {
            updateCurrentNode();
            updateCurrentNode.set(false);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateCurrentNode.set(true);
                }
            });
        }
    });

    templateTreeTableScrollPane = new JScrollPane(templateTreeTable);
    templateTreeTableScrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x6E6E6E)));

    templateFilterNotificationLabel = new JLabel();

    templateFilterLabel = new JLabel("Filter:");

    templateFilterField = new JTextField();
    templateFilterField.setToolTipText(
            "Filters (by name) the code templates and libraries that show up in the table above.");

    templateFilterField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        private void filterChanged(DocumentEvent evt) {
            try {
                updateTemplateFilter(evt.getDocument().getText(0, evt.getLength()));
            } catch (BadLocationException e) {
            }
        }
    });

    templateFilterField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent evt) {
            updateTemplateFilter(templateFilterField.getText());
        }
    });

    blankPanel = new JPanel();

    libraryPanel = new JPanel();
    libraryPanel.setBackground(splitPane.getBackground());

    libraryLeftPanel = new JPanel();
    libraryLeftPanel.setBackground(libraryPanel.getBackground());

    librarySummaryLabel = new JLabel("Summary:");
    librarySummaryValue = new JLabel();

    libraryDescriptionLabel = new JLabel("Description:");
    libraryDescriptionScrollPane = new MirthRTextScrollPane(null, false, SyntaxConstants.SYNTAX_STYLE_NONE,
            false);

    DocumentListener codeChangeListener = new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent evt) {
            codeChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            codeChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            codeChanged();
        }

        private void codeChanged() {
            if (codeChangeWorker != null) {
                codeChangeWorker.cancel(true);
            }

            int selectedRow = templateTreeTable.getSelectedRow();
            if (selectedRow >= 0) {
                TreePath selectedPath = templateTreeTable.getPathForRow(selectedRow);
                if (selectedPath != null) {
                    codeChangeWorker = new CodeChangeWorker(
                            (String) ((TreeTableNode) selectedPath.getLastPathComponent())
                                    .getValueAt(TEMPLATE_ID_COLUMN));
                    codeChangeWorker.execute();
                }
            }
        }
    };
    libraryDescriptionScrollPane.getDocument().addDocumentListener(codeChangeListener);

    libraryRightPanel = new JPanel();
    libraryRightPanel.setBackground(libraryPanel.getBackground());

    libraryChannelsSelectPanel = new JPanel();
    libraryChannelsSelectPanel.setBackground(libraryRightPanel.getBackground());

    libraryChannelsLabel = new JLabel("<html><b>Channels</b></html>");
    libraryChannelsLabel.setForeground(new Color(64, 64, 64));

    libraryChannelsSelectAllLabel = new JLabel("<html><u>Select All</u></html>");
    libraryChannelsSelectAllLabel.setForeground(Color.BLUE);
    libraryChannelsSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    libraryChannelsSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            if (evt.getComponent().isEnabled()) {
                for (int row = 0; row < libraryChannelsTable.getRowCount(); row++) {
                    ChannelInfo channelInfo = (ChannelInfo) libraryChannelsTable.getValueAt(row,
                            LIBRARY_CHANNELS_NAME_COLUMN);
                    channelInfo.setEnabled(true);
                    libraryChannelsTable.setValueAt(channelInfo, row, LIBRARY_CHANNELS_NAME_COLUMN);
                }
                setSaveEnabled(true);
            }
        }
    });

    libraryChannelsDeselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    libraryChannelsDeselectAllLabel.setForeground(Color.BLUE);
    libraryChannelsDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    libraryChannelsDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            if (evt.getComponent().isEnabled()) {
                for (int row = 0; row < libraryChannelsTable.getRowCount(); row++) {
                    ChannelInfo channelInfo = (ChannelInfo) libraryChannelsTable.getValueAt(row,
                            LIBRARY_CHANNELS_NAME_COLUMN);
                    channelInfo.setEnabled(false);
                    libraryChannelsTable.setValueAt(channelInfo, row, LIBRARY_CHANNELS_NAME_COLUMN);
                }
                setSaveEnabled(true);
            }
        }
    });

    libraryChannelsFilterLabel = new JLabel("Filter:");
    libraryChannelsFilterField = new JTextField();
    libraryChannelsFilterField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }
    });

    libraryChannelsTable = new MirthTable();
    libraryChannelsTable.setModel(new RefreshTableModel(new Object[] { "Name", "Id" }, 0));
    libraryChannelsTable.setDragEnabled(false);
    libraryChannelsTable.setRowSelectionAllowed(false);
    libraryChannelsTable.setRowHeight(UIConstants.ROW_HEIGHT);
    libraryChannelsTable.setFocusable(false);
    libraryChannelsTable.setOpaque(true);
    libraryChannelsTable.getTableHeader().setReorderingAllowed(false);
    libraryChannelsTable.setEditable(true);

    OffsetRowSorter libraryChannelsRowSorter = new OffsetRowSorter(libraryChannelsTable.getModel(), 1);
    libraryChannelsRowSorter.setRowFilter(new RowFilter<TableModel, Integer>() {
        @Override
        public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
            String name = entry.getStringValue(LIBRARY_CHANNELS_NAME_COLUMN);
            return name.equals(NEW_CHANNELS) || StringUtils.containsIgnoreCase(name,
                    StringUtils.trim(libraryChannelsFilterField.getText()));
        }
    });
    libraryChannelsTable.setRowSorter(libraryChannelsRowSorter);

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

    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_NAME_COLUMN)
            .setCellRenderer(new ChannelsTableCellRenderer());
    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_NAME_COLUMN)
            .setCellEditor(new ChannelsTableCellEditor());

    // Hide ID column
    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_ID_COLUMN).setVisible(false);

    libraryChannelsScrollPane = new JScrollPane(libraryChannelsTable);

    templatePanel = new JPanel();
    templatePanel.setBackground(splitPane.getBackground());

    templateLeftPanel = new JPanel();
    templateLeftPanel.setBackground(templatePanel.getBackground());

    templateLibraryLabel = new JLabel("Library:");
    templateLibraryComboBox = new JComboBox<String>();
    templateLibraryComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            libraryComboBoxActionPerformed();
        }
    });

    templateTypeLabel = new JLabel("Type:");
    templateTypeComboBox = new JComboBox<CodeTemplateType>(CodeTemplateType.values());
    templateTypeComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            setSaveEnabled(true);
        }
    });

    templateCodeLabel = new JLabel("Code:");
    templateCodeTextArea = new MirthRTextScrollPane(ContextType.GLOBAL_DEPLOY);
    templateCodeTextArea.getDocument().addDocumentListener(codeChangeListener);

    templateAutoGenerateDocumentationButton = new JButton("Update JSDoc");
    templateAutoGenerateDocumentationButton.setToolTipText(
            "<html>Generates/updates a JSDoc at the beginning of your<br/>code, with parameter/return annotations as needed.</html>");
    templateAutoGenerateDocumentationButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            String currentText = templateCodeTextArea.getText();
            String newText = CodeTemplateUtil.updateCode(templateCodeTextArea.getText());
            templateCodeTextArea.setText(newText, false);
            if (!currentText.equals(newText)) {
                setSaveEnabled(true);
            }
        }
    });

    templateRightPanel = new JPanel();
    templateRightPanel.setBackground(templatePanel.getBackground());

    templateContextSelectPanel = new JPanel();
    templateContextSelectPanel.setBackground(templateRightPanel.getBackground());

    templateContextLabel = new JLabel("<html><b>Context</b></html>");
    templateContextLabel.setForeground(new Color(64, 64, 64));

    templateContextSelectAllLabel = new JLabel("<html><u>Select All</u></html>");
    templateContextSelectAllLabel.setForeground(Color.BLUE);
    templateContextSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    templateContextSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            TreeTableNode root = (TreeTableNode) templateContextTreeTable.getTreeTableModel().getRoot();
            for (Enumeration<? extends TreeTableNode> groups = root.children(); groups.hasMoreElements();) {
                TreeTableNode group = groups.nextElement();
                ((MutablePair<Integer, String>) group.getUserObject()).setLeft(MirthTriStateCheckBox.CHECKED);
                for (Enumeration<? extends TreeTableNode> children = group.children(); children
                        .hasMoreElements();) {
                    ((MutablePair<Integer, String>) children.nextElement().getUserObject())
                            .setLeft(MirthTriStateCheckBox.CHECKED);
                }
            }
            templateContextTreeTable.updateUI();
            setSaveEnabled(true);
        }
    });

    templateContextDeselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    templateContextDeselectAllLabel.setForeground(Color.BLUE);
    templateContextDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    templateContextDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            TreeTableNode root = (TreeTableNode) templateContextTreeTable.getTreeTableModel().getRoot();
            for (Enumeration<? extends TreeTableNode> groups = root.children(); groups.hasMoreElements();) {
                TreeTableNode group = groups.nextElement();
                ((MutablePair<Integer, String>) group.getUserObject()).setLeft(MirthTriStateCheckBox.UNCHECKED);
                for (Enumeration<? extends TreeTableNode> children = group.children(); children
                        .hasMoreElements();) {
                    ((MutablePair<Integer, String>) children.nextElement().getUserObject())
                            .setLeft(MirthTriStateCheckBox.UNCHECKED);
                }
            }
            templateContextTreeTable.updateUI();
            setSaveEnabled(true);
        }
    });

    final TableCellEditor contextCellEditor = new ContextTreeTableCellEditor(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            setSaveEnabled(true);
        }
    });

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

    DefaultMutableTreeTableNode rootContextNode = new DefaultMutableTreeTableNode();
    DefaultMutableTreeTableNode globalScriptsNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Global Scripts"));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_DEPLOY)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_UNDEPLOY)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_PREPROCESSOR)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_POSTPROCESSOR)));
    rootContextNode.add(globalScriptsNode);
    DefaultMutableTreeTableNode channelScriptsNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Channel Scripts"));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_DEPLOY)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_UNDEPLOY)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_PREPROCESSOR)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_POSTPROCESSOR)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_ATTACHMENT)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_BATCH)));
    rootContextNode.add(channelScriptsNode);
    DefaultMutableTreeTableNode sourceConnectorNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Source Connector"));
    sourceConnectorNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.SOURCE_RECEIVER)));
    sourceConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.SOURCE_FILTER_TRANSFORMER)));
    rootContextNode.add(sourceConnectorNode);
    DefaultMutableTreeTableNode destinationConnectorNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Destination Connector"));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_FILTER_TRANSFORMER)));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_DISPATCHER)));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_RESPONSE_TRANSFORMER)));
    rootContextNode.add(destinationConnectorNode);

    DefaultTreeTableModel contextModel = new SortableTreeTableModel(rootContextNode);
    contextModel.setColumnIdentifiers(Arrays.asList(new String[] { "Context" }));
    templateContextTreeTable.setTreeTableModel(contextModel);

    templateContextTreeTable.setRootVisible(false);
    templateContextTreeTable.setDragEnabled(false);
    templateContextTreeTable.setRowSelectionAllowed(false);
    templateContextTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    templateContextTreeTable.setFocusable(false);
    templateContextTreeTable.setOpaque(true);
    templateContextTreeTable.getTableHeader().setReorderingAllowed(false);
    templateContextTreeTable.setEditable(true);
    templateContextTreeTable.setSortable(false);
    templateContextTreeTable.setShowGrid(true, true);

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

    templateContextTreeTable.setTreeCellRenderer(new ContextTreeTableCellRenderer());
    templateContextTreeTable.setOpenIcon(null);
    templateContextTreeTable.setClosedIcon(null);
    templateContextTreeTable.setLeafIcon(null);

    templateContextTreeTable.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 (templateContextTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())) < 0) {
                templateContextTreeTable.clearSelection();
            }
        }
    });

    templateContextTreeTable.getTreeTableModel().addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeNodesChanged(TreeModelEvent evt) {
            if (ArrayUtils.isNotEmpty(evt.getChildren())) {
                TreeTableNode node = (TreeTableNode) evt.getChildren()[0];

                if (evt.getTreePath().getPathCount() == 2) {
                    boolean allChildren = true;
                    boolean noChildren = true;
                    for (Enumeration<? extends TreeTableNode> children = node.getParent().children(); children
                            .hasMoreElements();) {
                        TreeTableNode child = children.nextElement();
                        if (((Pair<Integer, ContextType>) child.getUserObject())
                                .getLeft() == MirthTriStateCheckBox.UNCHECKED) {
                            allChildren = false;
                        } else {
                            noChildren = false;
                        }
                    }

                    int value;
                    if (allChildren) {
                        value = MirthTriStateCheckBox.CHECKED;
                    } else if (noChildren) {
                        value = MirthTriStateCheckBox.UNCHECKED;
                    } else {
                        value = MirthTriStateCheckBox.PARTIAL;
                    }

                    ((MutablePair<Integer, String>) node.getParent().getUserObject()).setLeft(value);
                } else if (evt.getTreePath().getPathCount() == 1) {
                    int value = ((Pair<Integer, String>) node.getUserObject()).getLeft();

                    for (Enumeration<? extends TreeTableNode> children = node.children(); children
                            .hasMoreElements();) {
                        ((MutablePair<Integer, ContextType>) children.nextElement().getUserObject())
                                .setLeft(value);
                    }
                }
            }
        }

        @Override
        public void treeNodesInserted(TreeModelEvent evt) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent evt) {
        }

        @Override
        public void treeStructureChanged(TreeModelEvent evt) {
        }
    });

    templateContextTreeTableScrollPane = new JScrollPane(templateContextTreeTable);
}

From source file:base.BasePlayer.Main.java

void setMenuBar() {
    //filemenu.addMouseListener(this);

    //toolmenu.addMouseListener(this);
    filemenu = new JMenu("File");
    toolmenu = new JMenu("Tools");
    help = new JMenu("Help");
    about = new JMenu("About");
    menubar = new JMenuBar();
    //help.addMouseListener(this);
    exit = new JMenuItem("Exit");
    manual = new JButton("Online manual");
    manual.addActionListener(new ActionListener() {

        @Override/*w  ww . j a  v  a 2s .  co  m*/
        public void actionPerformed(ActionEvent arg0) {
            Main.gotoURL("https://baseplayer.fi/BPmanual");
        }

    });
    //   opensamples = new JMenuItem("Add samples");
    zoomout = new JButton("Zoom out");
    back = new JButton("<<");
    forward = new JButton(">>");
    manage = new JButton("Variant Manager");
    openvcfs = new JMenuItem("Add VCFs", open);
    openbams = new JMenuItem("Add BAMs", open);
    average = new JMenuItem("Coverage calculator");
    update = new JMenuItem("Update");
    update.setVisible(false);
    errorlog = new JMenuItem("View log");
    //helpLabel = new JLabel("This is pre-release version of BasePlayer\nContact: help@baseplayer.fi\n\nUniversity of Helsinki");

    addURL = new JMenu("Add from URL");
    urlField = new JTextField("Enter URL");
    addtracks = new JMenuItem("Add tracks");
    fromURL = new JMenuItem("Add track from URL");
    addcontrols = new JMenuItem("Add controls");
    pleiadesButton = new JMenuItem("PLEIADES");
    saveProject = new JMenuItem("Save project");
    saveProjectAs = new JMenuItem("Save project as...");
    openProject = new JMenuItem("Open project");
    clear = new JMenuItem("Clear data");
    clearMemory = new JMenuItem("Clean memory");
    //   welcome = new JMenuItem("Welcome screen");
    filemenu.add(openvcfs);
    filemenu.add(openbams);
    variantCaller = new JMenuItem("Variant Caller");
    tbrowser = new JMenuItem("Table Browser");
    bconvert = new JMenuItem("BED converter");
    peakCaller = new JMenuItem("Peak Caller");
    addtracks = new JMenuItem("Add tracks", open);
    filemenu.add(addtracks);
    addcontrols = new JMenuItem("Add controls", open);
    filemenu.add(addcontrols);
    filemenu.add(fromURL);
    if (pleiades) {
        pleiadesButton.setPreferredSize(buttonDimension);
        pleiadesButton.addActionListener(this);

        filemenu.add(pleiadesButton);
    }

    filemenu.add(new JSeparator());
    openProject = new JMenuItem("Open project", open);
    filemenu.add(openProject);
    saveProject = new JMenuItem("Save project", save);
    filemenu.add(saveProject);
    saveProjectAs = new JMenuItem("Save project as...", save);
    filemenu.add(saveProjectAs);
    filemenu.add(new JSeparator());
    filemenu.add(genome);
    filemenu.add(update);
    filemenu.add(clear);
    filemenu.add(new JSeparator());
    filemenu.add(exit);
    exit.addActionListener(this);
    menubar.add(filemenu);
    manage.addActionListener(this);
    manage.addMouseListener(this);
    update.addActionListener(this);
    average.addActionListener(this);
    average.setEnabled(false);
    average.setToolTipText("No bam/cram files opened");
    tbrowser.addActionListener(this);
    bconvert.addActionListener(this);
    toolmenu.add(tbrowser);
    toolmenu.add(average);
    toolmenu.add(variantCaller);
    toolmenu.add(bconvert);
    fromURL.addMouseListener(this);
    fromURL.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            final JPopupMenu menu = new JPopupMenu();
            final JTextField area = new JTextField();
            JButton add = new JButton("Fetch");
            JLabel label = new JLabel("Paste track URL below");
            JScrollPane menuscroll = new JScrollPane();
            add.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        String urltext = area.getText().trim();
                        Boolean size = true;
                        if (urltext.contains("pleiades")) {
                            openPleiades(urltext);
                            return;
                        }
                        if (!FileRead.isTrackFile(urltext)) {
                            showError("The file format is not supported.\n"
                                    + "Supported formats: bed, bigwig, bigbed, gff, bedgraph", "Error");
                            return;

                        }
                        if (!urltext.toLowerCase().endsWith(".bw") && !urltext.toLowerCase().endsWith(".bigwig")
                                && !urltext.toLowerCase().endsWith(".bb")
                                && !urltext.toLowerCase().endsWith(".bigbed")) {
                            URL url = null;
                            try {
                                url = new URL(urltext);
                            } catch (Exception ex) {
                                menu.setVisible(false);
                                Main.showError("Please paste whole url (protocol included)", "Error");
                                return;
                            }
                            URL testurl = url;
                            HttpURLConnection huc = (HttpURLConnection) testurl.openConnection();
                            huc.setRequestMethod("HEAD");
                            int responseCode = huc.getResponseCode();

                            if (responseCode != 404) {

                                SeekableStream stream = SeekableStreamFactory.getInstance().getStreamFor(url);
                                TabixReader tabixReader = null;
                                String index = null;

                                try {
                                    if (stream.length() / (double) 1048576 >= Settings.settings
                                            .get("bigFile")) {
                                        size = false;
                                    }
                                    tabixReader = new TabixReader(urltext, urltext + ".tbi", stream);

                                    index = urltext + ".tbi";
                                    testurl = new URL(index);
                                    huc = (HttpURLConnection) testurl.openConnection();
                                    huc.setRequestMethod("HEAD");
                                    responseCode = huc.getResponseCode();

                                    if (responseCode == 404) {
                                        menu.setVisible(false);
                                        Main.showError("Index file (.tbi) not found in the URL.", "Error");

                                        return;
                                    }

                                } catch (Exception ex) {
                                    try {
                                        tabixReader = new TabixReader(urltext,
                                                urltext.substring(0, urltext.indexOf(".gz")) + ".tbi", stream);
                                        index = urltext.substring(0, urltext.indexOf(".gz")) + ".tbi";
                                    } catch (Exception exc) {
                                        menu.setVisible(false);
                                        Main.showError("Could not read tabix file.", "Error");
                                    }
                                }
                                if (tabixReader != null && index != null) {
                                    stream.close();
                                    tabixReader.close();
                                    menu.setVisible(false);
                                    FileRead filereader = new FileRead();
                                    filereader.readBED(urltext, index, size);

                                }

                            } else {
                                menu.setVisible(false);
                                Main.showError("Not a valid URL", "Error");
                            }

                        } else {
                            URL url = null;
                            try {
                                url = new URL(urltext);
                            } catch (Exception ex) {
                                Main.showError("Please paste whole url (protocol included)", "Error");
                                return;
                            }
                            final URL testurl = url;
                            HttpURLConnection huc = (HttpURLConnection) testurl.openConnection();
                            huc.setRequestMethod("HEAD");
                            int responseCode = huc.getResponseCode();

                            if (responseCode != 404) {
                                menu.setVisible(false);
                                FileRead filereader = new FileRead();

                                filereader.readBED(urltext, "nan", true);

                            } else {
                                menu.setVisible(false);
                                Main.showError("Not a valid URL", "Error");
                            }

                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }

            });
            area.setFont(Main.menuFont);
            //area.setText("https://baseplayer.fi/tracks/Mappability_1000Genomes_pilot_mask.bed.gz");
            menu.add(label);
            menu.add(menuscroll);
            menu.add(add);
            area.setPreferredSize(new Dimension(300, Main.defaultFontSize + 8));

            area.setCaretPosition(0);
            area.revalidate();
            menuscroll.getViewport().add(area);
            area.requestFocus();
            menu.pack();

            menu.show(frame, mouseX + 20, fromURL.getY());
        }

    });
    //toolmenu.add(peakCaller);
    variantCaller.setToolTipText("No bam/cram files opened");
    variantCaller.addActionListener(this);
    variantCaller.setEnabled(false);
    peakCaller.setEnabled(true);
    peakCaller.addActionListener(this);
    settings.addActionListener(this);
    clearMemory.addActionListener(this);
    errorlog.addActionListener(this);
    toolmenu.add(clearMemory);
    toolmenu.add(errorlog);
    toolmenu.add(new JSeparator());
    toolmenu.add(settings);
    menubar.add(toolmenu);
    menubar.add(manage);
    area = new JEditorPane();

    String infotext = "<html><h2>BasePlayer</h2>This is a version " + version
            + " of BasePlayer (<a href=https://baseplayer.fi>https://baseplayer.fi</a>)<br/> Author: Riku Katainen <br/> University of Helsinki<br/>"
            + "Tumor Genomics Group (<a href=http://research.med.helsinki.fi/gsb/aaltonen/>http://research.med.helsinki.fi/gsb/aaltonen/</a>) <br/> "
            + "Contact: help@baseplayer.fi <br/> <br/>"

            + "Supported filetype for variants is VCF and VCF.gz (index file will be created if missing)<br/> "
            + "Supported filetypes for reads are BAM and CRAM. Index files required (.bai or .crai). <br/> "
            + "Supported filetypes for additional tracks are BED(.gz), GFF.gz, BedGraph, BigWig, BigBed.<br/> (tabix index required for bgzipped files). <br/><br/> "

            + "For optimal usage, you should have vcf.gz and bam -files for each sample. <br/> "
            + "e.g. in case you have a sample named as sample1, name all files similarly and <br/>"
            + "place in the same folder:<br/>" + "sample1.vcf.gz<br/>" + "sample1.vcf.gz.tbi<br/>"
            + "sample1.bam<br/>" + "sample1.bam.bai<br/><br/>"
            + "When you open sample1.vcf.gz, sample1.bam is recognized and opened<br/>"
            + "on the same track.<br/><br/>"
            + "Instructional videos can be viewed at our <a href=https://www.youtube.com/channel/UCywq-T7W0YPzACyB4LT7Q3g> Youtube channel</a>";
    area = new JEditorPane();
    area.setEditable(false);
    area.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
    area.setText(infotext);
    area.setFont(Main.menuFont);
    area.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
            HyperlinkEvent.EventType type = hyperlinkEvent.getEventType();
            final URL url = hyperlinkEvent.getURL();
            if (type == HyperlinkEvent.EventType.ACTIVATED) {
                Main.gotoURL(url.toString());
            }
        }
    });

    about.add(area);
    about.addMouseListener(this);
    help.add(about);
    help.add(manual);
    menubar.add(help);
    JLabel emptylab = new JLabel("  ");
    emptylab.setEnabled(false);
    emptylab.setOpaque(false);
    menubar.add(emptylab);

    chromosomeDropdown.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 1, Color.lightGray));
    chromosomeDropdown.setBorder(BorderFactory.createCompoundBorder(chromosomeDropdown.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));

    chromlabel.setToolTipText("Current chromosome");
    chromlabel.setFocusable(false);
    chromlabel.addMouseListener(this);
    chromlabel.setBackground(Color.white);
    chromlabel.setEditable(false);
    chromlabel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Color.lightGray));
    chromlabel.setBorder(BorderFactory.createCompoundBorder(chromlabel.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));
    menubar.add(chromlabel);
    chromosomeDropdown.setBackground(Color.white);
    chromosomeDropdown.setToolTipText("Current chromosome");
    menubar.add(chromosomeDropdown);
    JLabel empty3 = new JLabel("  ");
    empty3.setEnabled(false);
    empty3.setOpaque(false);
    menubar.add(empty3);
    menubar.add(back);
    menubar.add(searchField);
    searchField.setForeground(Color.gray);
    searchField.setBorder(BorderFactory.createCompoundBorder(searchField.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));

    searchField.addMouseListener(this);
    menubar.add(back);
    menubar.add(searchField);
    searchField.setForeground(Color.gray);

    back.addMouseListener(this);
    back.setToolTipText("Back");
    forward.addMouseListener(this);
    forward.setToolTipText("Forward");
    back.setEnabled(false);
    forward.setEnabled(false);

    searchField.addMouseListener(this);

    menubar.add(back);
    menubar.add(searchField);
    searchField.setForeground(Color.gray);
    back.addMouseListener(this);
    forward.addMouseListener(this);
    back.setEnabled(false);
    forward.setEnabled(false);
    forward.setMargin(new Insets(0, 2, 0, 2));
    back.setMargin(new Insets(0, 2, 0, 2));
    menubar.add(forward);
    JLabel empty4 = new JLabel("  ");
    empty4.setOpaque(false);
    empty4.setEnabled(false);
    menubar.add(empty4);
    menubar.add(zoomout);
    JLabel empty5 = new JLabel("  ");
    empty5.setEnabled(false);
    empty5.setOpaque(false);
    menubar.add(empty5);
    positionField.setEditable(false);
    positionField.setBackground(new Color(250, 250, 250));

    positionField.setMargin(new Insets(0, 2, 0, 0));
    positionField.setBorder(BorderFactory.createCompoundBorder(widthLabel.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));
    menubar.add(positionField);
    widthLabel.setEditable(false);
    widthLabel.setBackground(new Color(250, 250, 250));
    widthLabel.setMargin(new Insets(0, 2, 0, 0));
    widthLabel.setBorder(BorderFactory.createCompoundBorder(widthLabel.getBorder(),
            BorderFactory.createEmptyBorder(0, 0, 0, 0)));
    JLabel empty6 = new JLabel("  ");
    empty6.setEnabled(false);
    empty6.setOpaque(false);
    menubar.add(empty6);
    menubar.add(widthLabel);
    JLabel empty7 = new JLabel("  ");
    empty7.setOpaque(false);
    empty7.setEnabled(false);
    menubar.add(empty7);
}

From source file:base.BasePlayer.Main.java

void setButtons() {
    try {//from w  ww  . j a v  a  2s . c o  m

        //      filemenu.setFont(font);
        GridBagConstraints c = new GridBagConstraints();

        c.anchor = GridBagConstraints.NORTHWEST;
        c.insets = new Insets(1, 4, 4, 2);
        //c.insets = new Insets(5, 5, 2, 5);
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 1;
        /*   opensamples.setMargin(new Insets(0, 0, 0,0));
                   
           opensamples.setPreferredSize(buttonDimension);
           addtracks.setMargin(new Insets(0, 0, 0, 0));
           addtracks.setPreferredSize(buttonDimension);
           addcontrols.setMargin(new Insets(0, 0, 0, 0));
           addcontrols.setPreferredSize(buttonDimension);
           */

        menubar.setOpaque(true);
        panel.add(menubar, c);
        c.gridx = 1;

        setbut = new JButton("", settingsIcon);
        setbut.setToolTipText("Settings");

        setbut.setOpaque(false);
        setbut.setContentAreaFilled(false);
        setbut.setBackground(Main.panel.getBackground());
        setbut.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {

            }

            @Override
            public void mousePressed(MouseEvent e) {
                Settings.frame.setLocation(
                        frame.getLocationOnScreen().x + frame.getWidth() / 2 - Settings.frame.getWidth() / 2,
                        frame.getLocationOnScreen().y + frame.getHeight() / 6);
                Settings.frame.setState(JFrame.NORMAL);
                Settings.frame.setVisible(true);
            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                setbut.setOpaque(true);
                Main.setbut.setBackground(Color.white);
                Main.setbut.revalidate();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                setbut.setOpaque(false);
                Main.setbut.revalidate();
            }

        });
        setbut.setBorder(null);
        c.insets = new Insets(0, 2, 0, 0);
        menubar.add(setbut, c);
        //   c.gridx = 1;
        //   c.gridx = 2;      
        //   c.gridx = 3;      

        //      zoomout.setMargin(new Insets(0, 0, 0, 0));
        //   panel.add(zoomout, c);      

        /*   JMenuItem empty2 = new JMenuItem("");
           empty2.setEnabled(false);      
           menubar.add(empty2);
                  
            c.gridx = 4;*/
        //  chromosomeDropdown.setPreferredSize(buttonDimension);

        // panel.add(chromosomeDropdown, c);
        //       c.gridx = 5;

        //  back.setMargin(new Insets(0, 0, 0, 0));
        // forward.setMargin(new Insets(0, 0, 0, 0));
        // back.setPreferredSize(new Dimension(back.getFontMetrics(back.getFont()).stringWidth("<")+10,(int)fieldDimension.getHeight()));
        //    forward.setPreferredSize(new Dimension(forward.getFontMetrics(forward.getFont()).stringWidth("<")+10,(int)fieldDimension.getHeight()));
        //back.setMinimumSize(new Dimension(back.getFontMetrics(back.getFont()).stringWidth("<")+10,(int)fieldDimension.getHeight()));
        //    forward.setMinimumSize(new Dimension(forward.getFontMetrics(forward.getFont()).stringWidth("<")+10,(int)fieldDimension.getHeight()));
        //    panel.add(back, c);
        //       c.gridx = 7;
        //   panel.add(forward, c);

        chromosomeDropdown.setMaximumRowCount(25);
        chromosomeDropdown.setEnabled(true);
        chromosomeDropdown.addActionListener(ChromoDropActionListener);
        chromosomeDropdown.addMouseListener(this);

        c.gridwidth = 10;
        c.gridx = 0;
        c.gridy = 1;
        bedScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        bedScroll.getViewport().setPreferredSize(bedDimensions);

        drawScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        drawScroll.getViewport().setPreferredSize(drawDimensions);

        chromScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        chromScroll.getViewport().setPreferredSize(chromDimensions);

        drawScroll.getVerticalScrollBar().setAutoscrolls(false);
        //       chromScroll.getViewport().setPreferredSize(new Dimension(drawWidth,chromHeight-20));

        //    drawScroll.setBorder(BorderFactory.createEmptyBorder());
        //chromScroll.setBorder(BorderFactory.createLoweredBevelBorder());
        //    drawScroll.setBorder(BorderFactory.createLoweredBevelBorder());
        //    bedScroll.setBorder(BorderFactory.createLoweredBevelBorder());

        //   chromScroll.setBorder(BorderFactory.createEmptyBorder());

        //       bedScroll.setBorder(BorderFactory.createEmptyBorder());

        controlScroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        controlScroll.getViewport().setPreferredSize(bedDimensions);
        controlScroll.getViewport().add(controlDraw);
        controlDraw.setVisible(false);
        controlScroll.setVisible(false);

        chromScroll.setBorder(BorderFactory.createEmptyBorder());
        drawScroll.setBorder(BorderFactory.createEmptyBorder());
        bedScroll.setBorder(BorderFactory.createLoweredBevelBorder());
        controlScroll.setBorder(BorderFactory.createLoweredBevelBorder());

        addSplit(chromosomeDropdown.getItemAt(0));

        chromScroll.getViewport().add(chromDraw);
        drawScroll.getViewport().add(drawCanvas);
        drawScroll.addMouseListener(this);
        bedCanvas = new BedCanvas(drawWidth, 200);

        bedScroll.getViewport().add(bedCanvas);

        frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);

        c.weightx = 1.0;
        c.weighty = 1.0;
        c.fill = GridBagConstraints.BOTH;

        trackPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, bedScroll, controlScroll);
        trackPane.setUI(new BasicSplitPaneUI() {
            public BasicSplitPaneDivider createDefaultDivider() {
                return new BasicSplitPaneDivider(this) {

                    private static final long serialVersionUID = 1L;

                    public void setBorder(Border b) {
                    }

                    @Override
                    public void paint(Graphics g) {
                        g.setColor(Color.lightGray);
                        g.fillRect(0, 0, getSize().width, getSize().height);
                        super.paint(g);
                    }
                };
            }
        });
        trackPane.setBorder(null);

        trackPane.setDividerSize(0);
        trackPane.setPreferredSize(drawDimensions);
        trackPane.setResizeWeight(0.0);
        trackPane.setContinuousLayout(true);
        trackPane.setVisible(false);

        varpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, trackPane, drawScroll);
        varpane.setUI(new BasicSplitPaneUI() {
            public BasicSplitPaneDivider createDefaultDivider() {
                return new BasicSplitPaneDivider(this) {

                    private static final long serialVersionUID = 1L;

                    public void setBorder(Border b) {
                    }

                    @Override
                    public void paint(Graphics g) {
                        g.setColor(Color.lightGray);
                        g.fillRect(0, 0, getSize().width, getSize().height);
                        super.paint(g);
                    }
                };
            }
        });
        varpane.setBorder(null);

        varpane.setDividerSize(0);
        varpane.setPreferredSize(drawDimensions);
        varpane.setResizeWeight(0.0);
        varpane.setContinuousLayout(true);
        bedScroll.setVisible(false);

        controlScroll.setVisible(false);

        chrompan = new JPanel() {
            private static final long serialVersionUID = 1L;

            protected void paintComponent(Graphics g) {

                super.paintComponent(g);
                g.setColor(Draw.sidecolor);
                g.fillRect(0, 0, this.getWidth(), this.getHeight());

                g.setColor(Color.gray);
                g.fillRect(0, 0, 3, this.getHeight());
                g.setColor(Color.lightGray);
                g.fillRect(2, 0, 2, this.getHeight());

            }

        };
        chrompan.setLayout(new GridBagLayout());
        GridBagConstraints gb = new GridBagConstraints();
        gb.anchor = GridBagConstraints.NORTHWEST;

        gb.insets = new Insets(2, 10, 2, 2);
        gb.gridx = 0;
        gb.gridy = 0;
        gb.gridwidth = 1;
        gb.fill = GridBagConstraints.HORIZONTAL;
        refDropdown.setBackground(Color.white);
        refDropdown.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.lightGray));
        refDropdown.setBorder(BorderFactory.createCompoundBorder(refDropdown.getBorder(),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)));
        geneDropdown.setBackground(Color.white);
        geneDropdown.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.lightGray));
        geneDropdown.setBorder(BorderFactory.createCompoundBorder(geneDropdown.getBorder(),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)));
        geneDropdown.addActionListener(annoDropActionListener);
        JLabel refLabel = new JLabel("Reference genome:");

        JLabel geneLabel = new JLabel("Gene annotation:");
        chromLabel.setName("header");
        chrompan.add(chromLabel, gb);
        gb.gridy++;
        chrompan.add(new JSeparator(), gb);
        gb.gridy++;
        gb.insets = new Insets(0, 10, 0, 2);
        chrompan.add(refLabel, gb);
        gb.gridy++;
        chrompan.add(refDropdown, gb);
        gb.gridy++;
        chrompan.add(geneLabel, gb);
        gb.gridy++;
        chrompan.add(geneDropdown, gb);
        gb.gridy++;
        gb.insets = new Insets(20, 10, 0, 2);
        JLabel memory = new JLabel("Memory usage:");
        memory.setName("header");
        chrompan.add(memory, gb);
        gb.insets = new Insets(0, 10, 0, 2);
        gb.gridy++;
        chrompan.add(memLabel, gb);
        gb.weightx = 1;
        gb.weighty = 1;
        gb.gridwidth = GridBagConstraints.REMAINDER;
        chrompan.add(new JLabel(), gb);
        chrompan.setMinimumSize(new Dimension(1, 1));
        chrompan.addComponentListener(this);
        upPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, chrompan, chromScroll);
        drawScroll.addComponentListener(this);
        //upPanel.setBorder(BorderFactory.createLoweredBevelBorder());
        upPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.white));
        upPanel.setDividerLocation(Main.sidebarWidth - 2);
        chrompan.setBackground(Draw.sidecolor);
        BasicSplitPaneUI chromPaneUI = (BasicSplitPaneUI) upPanel.getUI();
        chromPaneDivider = chromPaneUI.getDivider();
        chromPaneDivider.addMouseListener(this);

        upPanel.setDividerSize(3);

        upPanel.setUI(new BasicSplitPaneUI() {
            public BasicSplitPaneDivider createDefaultDivider() {
                return new BasicSplitPaneDivider(this) {

                    private static final long serialVersionUID = 1L;

                    public void setBorder(Border b) {
                    }

                    @Override
                    public void paint(Graphics g) {
                        g.setColor(Color.lightGray);
                        g.fillRect(0, 0, getSize().width, getSize().height);

                        super.paint(g);
                    }
                };
            }
        });

        splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upPanel, varpane);

        splitPane.setUI(new BasicSplitPaneUI() {
            public BasicSplitPaneDivider createDefaultDivider() {
                return new BasicSplitPaneDivider(this) {

                    private static final long serialVersionUID = 1L;

                    public void setBorder(Border b) {
                    }

                    @Override
                    public void paint(Graphics g) {
                        g.setColor(Color.lightGray);
                        g.fillRect(0, 0, getSize().width, getSize().height);

                        super.paint(g);
                    }
                };
            }
        });

        BasicSplitPaneUI basicSplitPaneUI = (BasicSplitPaneUI) splitPane.getUI();
        splitPaneDivider = basicSplitPaneUI.getDivider();
        //    splitPaneDivider.addMouseListener(this);
        basicSplitPaneUI = (BasicSplitPaneUI) trackPane.getUI();
        trackPaneDivider = basicSplitPaneUI.getDivider();
        //    trackPaneDivider.addMouseListener(this);
        BasicSplitPaneUI splitPaneUI = (BasicSplitPaneUI) varpane.getUI();
        varPaneDivider = splitPaneUI.getDivider();
        //   varPaneDivider.addMouseListener(this);
        splitPane.setDividerSize(3);

        splitPane.setPreferredSize(drawDimensions);
        splitPane.setContinuousLayout(true);

        panel.add(splitPane, c);
        add(panel, c);

        openvcfs.addActionListener(this);
        openbams.addActionListener(this);
        addtracks.addActionListener(this);
        addcontrols.addActionListener(this);

        openProject.addActionListener(this);
        saveProject.addActionListener(this);
        saveProjectAs.addActionListener(this);
        dosomething.addActionListener(this);
        clear.addActionListener(this);
        //    drawScroll.getVerticalScrollBar().addMouseMotionListener(this);
        drawScroll.getVerticalScrollBar().addMouseListener(this);
        drawScroll.getVerticalScrollBar().addMouseMotionListener(this);
        drawScroll.getVerticalScrollBar().addMouseWheelListener(new MouseWheelListener() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                Draw.setGlasspane(true);
                if (e.getWheelRotation() < 0) {
                    if (drawCanvas.drawVariables.visiblestart > 0) {
                        drawCanvas.drawVariables.visiblestart--;

                    }
                    Draw.setScrollbar((int) (drawCanvas.drawVariables.visiblestart
                            * drawCanvas.drawVariables.sampleHeight));
                } else {
                    if (drawCanvas.drawVariables.visiblestart
                            + drawCanvas.drawVariables.visiblesamples < Main.samples) {
                        drawCanvas.drawVariables.visiblestart++;

                    }
                    Draw.setScrollbar((int) (drawCanvas.drawVariables.visiblestart
                            * drawCanvas.drawVariables.sampleHeight));
                }

            }

        }

        );
        drawScroll.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {

            @Override
            public void adjustmentValueChanged(AdjustmentEvent event) {

                //System.out.println(drawCanvas.drawVariables.visiblestart +" " +(short)(Main.drawScroll.getVerticalScrollBar().getValue()/drawCanvas.drawVariables.sampleHeight));
                if (drawCanvas.drawVariables.visiblestart != (short) (Main.drawScroll.getVerticalScrollBar()
                        .getValue() / drawCanvas.drawVariables.sampleHeight)) {
                    if (!drawCanvas.sidebar) {
                        drawCanvas.drawVariables.visiblestart = (short) (Main.drawScroll.getVerticalScrollBar()
                                .getValue() / drawCanvas.drawVariables.sampleHeight);
                    }
                    if (drawCanvas.splits.size() > 1) {
                        for (int i = 0; i < drawCanvas.splits.size(); i++) {
                            drawCanvas.splits.get(i).updateReads = true;
                        }
                    } else {
                        Draw.updateReads = true;
                        Draw.updatevars = true;
                    }

                    Draw.updatevars = true;
                    Main.drawCanvas.repaint();
                }

            }

        });

        zoomout.addActionListener(this);

        FileRead.head = new VarNode(0, (byte) 0, "N", (short) 0, (short) 0, false, (float) 0, (float) 0, null,
                null, new Sample("", (short) 1, null), null, null);
        drawCanvas.current = FileRead.head;

        frame.addComponentListener(this);
        frame.addMouseListener(this);
        frame.setGlassPane(glassPane);
        glassPane.setOpaque(false);
        glassPane.setVisible(false);

        positionField.setText("chr1:1-" + MethodLibrary.formatNumber(drawCanvas.splits.get(0).chromEnd));
        positionField.setToolTipText("Current chromosomal region");
        widthLabel.setText(MethodLibrary.formatNumber(drawCanvas.splits.get(0).chromEnd) + "bp");
        widthLabel.setToolTipText("Current region width in base pairs");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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);
                }/*from  w  w w .j ava  2 s . c  om*/
                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:com.mirth.connect.client.ui.ChannelPanel.java

private void initComponents() {
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    splitPane.setOneTouchExpandable(true);

    topPanel = new JPanel();

    List<String> columns = new ArrayList<String>();

    for (ChannelColumnPlugin plugin : LoadedExtensions.getInstance().getChannelColumnPlugins().values()) {
        if (plugin.isDisplayFirst()) {
            columns.add(plugin.getColumnHeader());
        }//from  w  ww. j a va  2  s .  c  o m
    }

    columns.addAll(Arrays.asList(DEFAULT_COLUMNS));

    for (ChannelColumnPlugin plugin : LoadedExtensions.getInstance().getChannelColumnPlugins().values()) {
        if (!plugin.isDisplayFirst()) {
            columns.add(plugin.getColumnHeader());
        }
    }

    channelTable = new MirthTreeTable("channelPanel", new LinkedHashSet<String>(columns));

    channelTable.setColumnFactory(new ChannelTableColumnFactory());

    ChannelTreeTableModel model = new ChannelTreeTableModel();
    model.setColumnIdentifiers(columns);
    model.setNodeFactory(new DefaultChannelTableNodeFactory());
    channelTable.setTreeTableModel(model);

    channelTable.setDoubleBuffered(true);
    channelTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    channelTable.getTreeSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    channelTable.setHorizontalScrollEnabled(true);
    channelTable.packTable(UIConstants.COL_MARGIN);
    channelTable.setRowHeight(UIConstants.ROW_HEIGHT);
    channelTable.setOpaque(true);
    channelTable.setRowSelectionAllowed(true);
    channelTable.setSortable(true);
    channelTable.putClientProperty("JTree.lineStyle", "Horizontal");
    channelTable.setAutoCreateColumnsFromModel(false);
    channelTable.setShowGrid(true, true);
    channelTable.restoreColumnPreferences();
    channelTable.setMirthColumnControlEnabled(true);

    channelTable.setDragEnabled(true);
    channelTable.setDropMode(DropMode.ON);
    channelTable.setTransferHandler(new ChannelTableTransferHandler() {
        @Override
        public boolean canImport(TransferSupport support) {
            // Don't allow files to be imported when the save task is enabled 
            if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) && isSaveEnabled()) {
                return false;
            }
            return super.canImport(support);
        }

        @Override
        public void importFile(final File file, final boolean showAlerts) {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        String fileString = StringUtils.trim(parent.readFileToString(file));

                        try {
                            // If the table is in channel view, don't allow groups to be imported
                            ChannelGroup group = ObjectXMLSerializer.getInstance().deserialize(fileString,
                                    ChannelGroup.class);
                            if (group != null && !((ChannelTreeTableModel) channelTable.getTreeTableModel())
                                    .isGroupModeEnabled()) {
                                return;
                            }
                        } catch (Exception e) {
                        }

                        if (showAlerts && !parent.promptObjectMigration(fileString, "channel or group")) {
                            return;
                        }

                        try {
                            importChannel(
                                    ObjectXMLSerializer.getInstance().deserialize(fileString, Channel.class),
                                    showAlerts);
                        } catch (Exception e) {
                            try {
                                importGroup(ObjectXMLSerializer.getInstance().deserialize(fileString,
                                        ChannelGroup.class), showAlerts, !showAlerts);
                            } catch (Exception e2) {
                                if (showAlerts) {
                                    parent.alertThrowable(parent, e,
                                            "Invalid channel or group file:\n" + e.getMessage());
                                }
                            }
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean canMoveChannels(List<Channel> channels, int row) {
            if (row >= 0) {
                TreePath path = channelTable.getPathForRow(row);
                if (path != null) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) path.getLastPathComponent();

                    if (node.isGroupNode()) {
                        Set<String> currentChannelIds = new HashSet<String>();
                        for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                .children(); channelNodes.hasMoreElements();) {
                            currentChannelIds.add(((AbstractChannelTableNode) channelNodes.nextElement())
                                    .getChannelStatus().getChannel().getId());
                        }

                        for (Iterator<Channel> it = channels.iterator(); it.hasNext();) {
                            if (currentChannelIds.contains(it.next().getId())) {
                                it.remove();
                            }
                        }

                        return !channels.isEmpty();
                    }
                }
            }

            return false;
        }

        @Override
        public boolean moveChannels(List<Channel> channels, int row) {
            if (row >= 0) {
                TreePath path = channelTable.getPathForRow(row);
                if (path != null) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) path.getLastPathComponent();

                    if (node.isGroupNode()) {
                        Set<String> currentChannelIds = new HashSet<String>();
                        for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                .children(); channelNodes.hasMoreElements();) {
                            currentChannelIds.add(((AbstractChannelTableNode) channelNodes.nextElement())
                                    .getChannelStatus().getChannel().getId());
                        }

                        for (Iterator<Channel> it = channels.iterator(); it.hasNext();) {
                            if (currentChannelIds.contains(it.next().getId())) {
                                it.remove();
                            }
                        }

                        if (!channels.isEmpty()) {
                            ListSelectionListener[] listeners = ((DefaultListSelectionModel) channelTable
                                    .getSelectionModel()).getListSelectionListeners();
                            for (ListSelectionListener listener : listeners) {
                                channelTable.getSelectionModel().removeListSelectionListener(listener);
                            }

                            try {
                                ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable
                                        .getTreeTableModel();
                                Set<String> channelIds = new HashSet<String>();
                                for (Channel channel : channels) {
                                    model.addChannelToGroup(node, channel.getId());
                                    channelIds.add(channel.getId());
                                }

                                List<TreePath> selectionPaths = new ArrayList<TreePath>();
                                for (Enumeration<? extends MutableTreeTableNode> channelNodes = node
                                        .children(); channelNodes.hasMoreElements();) {
                                    AbstractChannelTableNode channelNode = (AbstractChannelTableNode) channelNodes
                                            .nextElement();
                                    if (channelIds
                                            .contains(channelNode.getChannelStatus().getChannel().getId())) {
                                        selectionPaths.add(new TreePath(
                                                new Object[] { model.getRoot(), node, channelNode }));
                                    }
                                }

                                parent.setSaveEnabled(true);
                                channelTable.expandPath(new TreePath(
                                        new Object[] { channelTable.getTreeTableModel().getRoot(), node }));
                                channelTable.getTreeSelectionModel().setSelectionPaths(
                                        selectionPaths.toArray(new TreePath[selectionPaths.size()]));
                                return true;
                            } finally {
                                for (ListSelectionListener listener : listeners) {
                                    channelTable.getSelectionModel().addListSelectionListener(listener);
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
    });

    channelTable.setTreeCellRenderer(new DefaultTreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
                    hasFocus);

            TreePath path = channelTable.getPathForRow(row);
            if (path != null && ((AbstractChannelTableNode) path.getLastPathComponent()).isGroupNode()) {
                setIcon(UIConstants.ICON_GROUP);
            }

            return label;
        }
    });
    channelTable.setLeafIcon(UIConstants.ICON_CHANNEL);
    channelTable.setOpenIcon(UIConstants.ICON_GROUP);
    channelTable.setClosedIcon(UIConstants.ICON_GROUP);

    channelTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            channelListSelected(evt);
        }
    });

    // listen for trigger button and double click to edit channel.
    channelTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelectionAndPopupMenu(evt);
        }

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

        @Override
        public void mouseClicked(MouseEvent evt) {
            int row = channelTable.rowAtPoint(new Point(evt.getX(), evt.getY()));
            if (row == -1) {
                return;
            }

            if (evt.getClickCount() >= 2 && channelTable.getSelectedRowCount() == 1
                    && channelTable.getSelectedRow() == row) {
                AbstractChannelTableNode node = (AbstractChannelTableNode) channelTable.getPathForRow(row)
                        .getLastPathComponent();
                if (node.isGroupNode()) {
                    doEditGroupDetails();
                } else {
                    doEditChannel();
                }
            }
        }
    });

    // Key Listener trigger for DEL
    channelTable.addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent evt) {
            if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
                if (channelTable.getSelectedModelRows().length == 0) {
                    return;
                }

                boolean allGroups = true;
                boolean allChannels = true;
                for (int row : channelTable.getSelectedModelRows()) {
                    AbstractChannelTableNode node = (AbstractChannelTableNode) channelTable.getPathForRow(row)
                            .getLastPathComponent();
                    if (node.isGroupNode()) {
                        allChannels = false;
                    } else {
                        allGroups = false;
                    }
                }

                if (allChannels) {
                    doDeleteChannel();
                } else if (allGroups) {
                    doDeleteGroup();
                }
            }
        }

        @Override
        public void keyReleased(KeyEvent evt) {
        }

        @Override
        public void keyTyped(KeyEvent evt) {
        }
    });

    // MIRTH-2301
    // Since we are using addHighlighter here instead of using setHighlighters, we need to remove the old ones first.
    channelTable.setHighlighters();

    // Set highlighter.
    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        channelTable.addHighlighter(highlighter);
    }

    HighlightPredicate revisionDeltaHighlighterPredicate = new HighlightPredicate() {
        @Override
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == channelTable.convertColumnIndexToView(
                    channelTable.getColumnExt(DEPLOYED_REVISION_DELTA_COLUMN_NAME).getModelIndex())) {
                if (channelTable.getValueAt(adapter.row, adapter.column) != null
                        && ((Integer) channelTable.getValueAt(adapter.row, adapter.column)).intValue() > 0) {
                    return true;
                }

                if (channelStatuses != null) {
                    String channelId = (String) channelTable.getModel()
                            .getValueAt(channelTable.convertRowIndexToModel(adapter.row), ID_COLUMN_NUMBER);
                    ChannelStatus status = channelStatuses.get(channelId);
                    if (status != null && status.isCodeTemplatesChanged()) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
    channelTable.addHighlighter(new ColorHighlighter(revisionDeltaHighlighterPredicate, new Color(255, 204, 0),
            Color.BLACK, new Color(255, 204, 0), Color.BLACK));

    HighlightPredicate lastDeployedHighlighterPredicate = new HighlightPredicate() {
        @Override
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == channelTable.convertColumnIndexToView(
                    channelTable.getColumnExt(LAST_DEPLOYED_COLUMN_NAME).getModelIndex())) {
                Calendar checkAfter = Calendar.getInstance();
                checkAfter.add(Calendar.MINUTE, -2);

                if (channelTable.getValueAt(adapter.row, adapter.column) != null
                        && ((Calendar) channelTable.getValueAt(adapter.row, adapter.column))
                                .after(checkAfter)) {
                    return true;
                }
            }
            return false;
        }
    };
    channelTable.addHighlighter(new ColorHighlighter(lastDeployedHighlighterPredicate, new Color(240, 230, 140),
            Color.BLACK, new Color(240, 230, 140), Color.BLACK));

    channelScrollPane = new JScrollPane(channelTable);
    channelScrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    filterPanel = new JPanel();
    filterPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(164, 164, 164)));

    tagsFilterButton = new IconButton();
    tagsFilterButton
            .setIcon(new ImageIcon(getClass().getResource("/com/mirth/connect/client/ui/images/wrench.png")));
    tagsFilterButton.setToolTipText("Show Channel Filter");
    tagsFilterButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            tagsFilterButtonActionPerformed();
        }
    });

    tagsLabel = new JLabel();

    ButtonGroup tableModeButtonGroup = new ButtonGroup();

    tableModeGroupsButton = new IconToggleButton(UIConstants.ICON_GROUP);
    tableModeGroupsButton.setToolTipText("Groups");
    tableModeGroupsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (!switchTableMode(true)) {
                tableModeChannelsButton.setSelected(true);
            }
        }
    });
    tableModeButtonGroup.add(tableModeGroupsButton);

    tableModeChannelsButton = new IconToggleButton(UIConstants.ICON_CHANNEL);
    tableModeChannelsButton.setToolTipText("Channels");
    tableModeChannelsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (!switchTableMode(false)) {
                tableModeGroupsButton.setSelected(true);
            }
        }
    });
    tableModeButtonGroup.add(tableModeChannelsButton);

    tabPane = new JTabbedPane();

    splitPane.setTopComponent(topPanel);
    splitPane.setBottomComponent(tabPane);
}