Example usage for javax.swing AbstractAction AbstractAction

List of usage examples for javax.swing AbstractAction AbstractAction

Introduction

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

Prototype

public AbstractAction() 

Source Link

Document

Creates an Action .

Usage

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

public void setCustomEditorControls(boolean enabled) {
    if (enabled) {
        // An action to toggle cell editing with the 'Enter' key.
        Action toggleEditing = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                if (isEditing()) {
                    getCellEditor().stopCellEditing();
                } else {
                    boolean success = editCellAt(getSelectedRow(), getSelectedColumn(), e);

                    if (success) {
                        // Request focus for TextFieldCellEditors
                        if (getCellEditor() instanceof TextFieldCellEditor) {
                            ((TextFieldCellEditor) getCellEditor()).getTextField().requestFocusInWindow();
                        }//from w w w .j  a v  a 2s . c  o m
                    }
                }
            }
        };

        /*
         * Don't edit cells on any keystroke. Let the toggleEditing action handle it for 'Enter'
         * only. Also surrender focus to any activated editor.
         */
        setAutoStartEditOnKeyStroke(false);
        setSurrendersFocusOnKeystroke(true);
        getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "toggleEditing");
        getActionMap().put("toggleEditing", toggleEditing);
    } else {
        setAutoStartEditOnKeyStroke(true);
        setSurrendersFocusOnKeystroke(false);
        getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "selectNextRowCell");
    }
}

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

protected void initComponent() {
    layout = new MigLayout("flowy, fill, insets 0", "", "[min!][fill]");
    panel = new JPanel(layout);

    topPanel = new JPanel(new BorderLayout());
    topPanel.setVisible(false);//w  ww .j  a  va 2  s. c om
    panel.add(topPanel, "growx");

    scrollPane = new JScrollPane(impl);
    impl.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    impl.setFillsViewportHeight(true);
    panel.add(scrollPane, "grow");

    impl.setShowGrid(true);
    impl.setGridColor(Color.lightGray);

    impl.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                handleClickAction();
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            showPopup(e);
        }

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

        protected void showPopup(MouseEvent e) {
            if (e.isPopupTrigger() && contextMenuEnabled) {
                // select row
                Point p = e.getPoint();
                int viewRowIndex = impl.rowAtPoint(p);

                int rowNumber;
                if (viewRowIndex >= 0) {
                    rowNumber = impl.convertRowIndexToModel(viewRowIndex);
                } else {
                    rowNumber = -1;
                }
                ListSelectionModel model = impl.getSelectionModel();

                if (!model.isSelectedIndex(rowNumber)) {
                    model.setSelectionInterval(rowNumber, rowNumber);
                }

                // show popup menu
                JPopupMenu popupMenu = createPopupMenu();
                if (popupMenu.getComponentCount() > 0) {
                    popupMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }
    });

    ColumnControlButton columnControlButton = new ColumnControlButton(impl) {
        @Override
        protected ColumnVisibilityAction createColumnVisibilityAction(TableColumn column) {
            ColumnVisibilityAction columnVisibilityAction = super.createColumnVisibilityAction(column);

            columnVisibilityAction.addPropertyChangeListener(evt -> {
                if ("SwingSelectedKey".equals(evt.getPropertyName()) && evt.getNewValue() instanceof Boolean) {
                    ColumnVisibilityAction action = (ColumnVisibilityAction) evt.getSource();

                    String columnName = action.getActionCommand();
                    boolean collapsed = !((boolean) evt.getNewValue());

                    Column col = getColumn(columnName);
                    if (col != null) {
                        col.setCollapsed(collapsed);
                    }
                }
            });

            return columnVisibilityAction;
        }
    };
    impl.setColumnControl(columnControlButton);

    impl.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");
    impl.getActionMap().put("enter", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (enterPressAction != null) {
                enterPressAction.actionPerform(DesktopAbstractTable.this);
            } else {
                handleClickAction();
            }
        }
    });

    Messages messages = AppBeans.get(Messages.NAME);
    // localize default column control actions
    for (Object actionKey : impl.getActionMap().allKeys()) {
        if ("column.packAll".equals(actionKey)) {
            BoundAction action = (BoundAction) impl.getActionMap().get(actionKey);
            action.setName(messages.getMessage(DesktopTable.class, "DesktopTable.packAll"));
        } else if ("column.packSelected".equals(actionKey)) {
            BoundAction action = (BoundAction) impl.getActionMap().get(actionKey);
            action.setName(messages.getMessage(DesktopTable.class, "DesktopTable.packSelected"));
        } else if ("column.horizontalScroll".equals(actionKey)) {
            BoundAction action = (BoundAction) impl.getActionMap().get(actionKey);
            action.setName(messages.getMessage(DesktopTable.class, "DesktopTable.horizontalScroll"));
        }
    }

    // Ability to configure fonts in table
    // Add action to column control
    String configureFontsLabel = messages.getMessage(DesktopTable.class, "DesktopTable.configureFontsLabel");
    impl.getActionMap().put(ColumnControlButton.COLUMN_CONTROL_MARKER + "fonts",
            new AbstractAction(configureFontsLabel) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Component rootComponent = SwingUtilities.getRoot(impl);
                    final FontDialog fontDialog = FontDialog.show(rootComponent, impl.getFont());
                    fontDialog.addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosed(WindowEvent e) {
                            Font result = fontDialog.getResult();
                            if (result != null) {
                                impl.setFont(result);
                                packRows();
                            }
                        }
                    });
                    fontDialog.open();
                }
            });

    // Ability to reset settings
    String resetSettingsLabel = messages.getMessage(DesktopTable.class, "DesktopTable.resetSettings");
    impl.getActionMap().put(ColumnControlButton.COLUMN_CONTROL_MARKER + "resetSettings",
            new AbstractAction(resetSettingsLabel) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    resetPresentation();
                }
            });

    scrollPane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            if (!columnsInitialized) {
                adjustColumnHeaders();
            }
            columnsInitialized = true;
        }
    });

    // init default row height
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            if (!fontInitialized) {
                applyFont(impl, impl.getFont());
            }
        }
    });
}

From source file:nz.govt.natlib.ndha.manualdeposit.jobmanagement.JobQueueManagement.java

private void checkJobQueue() {
    LOG.debug("Start checkJobQueue");
    boolean itemsMoved = checkAndMoveJobs(jobQueueRunning) || checkAndMoveJobs(jobQueuePending)
            || checkAndMoveJobs(jobQueueFailed) || checkAndMoveJobs(jobQueueDeposited)
            || checkAndMoveJobs(jobQueueInPermanent) || checkAndMoveJobs(jobQueueAwaitingCleanup);
    while ((!jobQueuePending.isEmpty())
            && (jobQueueRunning.size() < theAppProperties.getApplicationData().getMaximumJobsRunning())) {
        UploadJob job;/*from   w ww .  j  a v a  2 s .  c  o m*/
        // need to take either the first or last depending on whether the
        // queue is sorted Asc or Desc
        int jobNumber;
        if (personalSettings.isSortPendingAscending()) {
            jobNumber = 0;
        } else {
            jobNumber = jobQueuePending.size() - 1;
        }
        job = jobQueuePending.get(jobNumber);
        while (job.isCreatingCopy() && jobNumber >= 0 && jobNumber < jobQueuePending.size()) {
            if (personalSettings.isSortPendingAscending()) {
                jobNumber++;
            } else {
                jobNumber--;
            }
            if (jobNumber >= 0 && jobNumber < jobQueuePending.size()) {
                job = jobQueuePending.get(jobNumber);
            }
        }
        if (job.isCreatingCopy()) {
            break;
        }
        if (job.lock()) {
            jobQueuePending.remove(job);
            jobQueueRunning.add(job);
            itemsMoved = true;
            Thread t = new Thread(job);
            t.start();
            job.unlock();
        } else {
            LOG.debug("Couldn't lock job " + job.getJobDetail().get(0).getEntityName());
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
            }
        }
    }
    if (itemsMoved) {
        refreshJobQueue();
    }
    if (theJobQueuePendingTable != null) {
        theJobQueuePendingTable.repaint();
    }
    if (theJobQueueRunningTable != null) {
        theJobQueueRunningTable.repaint();
    }
    if (theJobQueueFailedTable != null) {
        theJobQueueFailedTable.repaint();
    }
    if (theJobQueueDepositedTable != null) {
        theJobQueueDepositedTable.repaint();
    }
    if (theJobQueueInPermanentTable != null) {
        theJobQueueInPermanentTable.repaint();
    }
    final Action checkJobQueueAction = new AbstractAction() {
        private static final long serialVersionUID = 5562669711772031634L;

        public void actionPerformed(final ActionEvent e) {
            Timer t = (Timer) e.getSource();
            t.stop();
            checkJobQueue();
        }
    };
    new Timer(theAppProperties.getApplicationData().getJobQueueRefreshInterval(), checkJobQueueAction).start();
    LOG.debug("End checkJobQueue");
}

From source file:ec.ui.view.MarginView.java

private JMenu buildMenu() {
    JMenu result = new JMenu();

    result.add(new JCheckBoxMenuItem(new AbstractAction() {
        @Override/* www  .  j  a va 2s .c  o  m*/
        public void actionPerformed(ActionEvent e) {
            setPrecisionMarkersVisible(!isPrecisionMarkersVisible());
        }
    })).setText("Show precision gradient");

    result.add(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            TsCollection col = TsFactory.instance.createTsCollection();
            col.add(TsFactory.instance.createTs("series", null, data.series));
            col.add(TsFactory.instance.createTs("lower", null, data.lower));
            col.add(TsFactory.instance.createTs("upper", null, data.upper));
            Transferable t = TssTransferSupport.getDefault().fromTsCollection(col);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(t, null);
        }
    }).setText("Copy all series");

    JMenu export = new JMenu("Export image to");
    export.add(ChartCommand.printImage().toAction(chartPanel)).setText("Printer...");
    export.add(ChartCommand.copyImage().toAction(chartPanel)).setText("Clipboard");
    export.add(ChartCommand.saveImage().toAction(chartPanel)).setText("File...");
    result.add(export);

    return result;
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositMain.java

@SuppressWarnings("serial")
public void setupScreen(final AppProperties appProperties, final String settingsPath) throws Exception {
    LOG.debug("setupScreen");
    this.setJMenuBar(mnuMain);
    theSettingsPath = settingsPath;//from ww w.j  a  v a2s .  co m
    LOG.debug("setupScreen, setting provenance event presenter");
    theAppProperties = appProperties;
    theUserGroupData = theAppProperties.getUserData().getUser(theAppProperties.getLoggedOnUser())
            .getUserGroupData();
    final boolean searchVisible = (theUserGroupData.isIncludeCMS2Search()
            || theUserGroupData.isIncludeCMS1Search() || theUserGroupData.isIncludeProducerList()
            || theUserGroupData.isIncludeNoCMSOption());
    pnlCmsReference.setVisible(searchVisible);
    mnuViewShowSearch.setVisible(searchVisible);
    if (theUserGroupData.isIncludeCMS2Search()) {
        rbnCMS2.setSelected(true);
    } else if (theUserGroupData.isIncludeCMS1Search()) {
        rbnCMS1.setSelected(true);
    } else if (theUserGroupData.isIncludeProducerList()) {
        rbnStaffMediated.setSelected(true);
    } else if (theUserGroupData.isIncludeNoCMSOption()) {
        rbnNoCmsRef.setSelected(true);
    }
    rbnCMS2.setVisible(theUserGroupData.isIncludeCMS2Search());
    rbnCMS1.setVisible(theUserGroupData.isIncludeCMS1Search());
    rbnNoCmsRef.setVisible(theUserGroupData.isIncludeNoCMSOption());
    rbnStaffMediated.setVisible(theUserGroupData.isIncludeProducerList());
    rbnCMS1.setText(theAppProperties.getApplicationData().getCMS1Label());
    rbnCMS2.setText(theAppProperties.getApplicationData().getCMS2Label());
    if (theUserGroupData.isIncludeCMS2Search()) {
        rbnCMS2.setSelected(true);
    } else {
        if (theUserGroupData.isIncludeCMS1Search()) {
            rbnCMS1.setSelected(true);
        } else {
            rbnNoCmsRef.setSelected(true);
        }
    }
    setTitle(title + theAppProperties.getAppVersion());
    ClassLoader cLoader = Thread.currentThread().getContextClassLoader();
    java.net.URL imageURL = cLoader.getResource("Indigo_logo_64x64.jpg");
    setIconImage(Toolkit.getDefaultToolkit().getImage(imageURL));
    LOG.debug("setupScreen, setting FormControl");
    try {
        theFormControl = new FormControl(this, theSettingsPath);
        fixBackwardsCompatibility();
    } catch (Exception ex) {
        LOG.error("Error loading form parameters", ex);
    }
    LOG.debug("setupScreen, adding handlers");
    depositPresenter.addHandlers(treeFileSystem, treeEntities, treeStructMap, cmbSelectTemplate,
            cmbSelectStructTemplate, cmbSortBy, cmbFixityType, tblDetail, tblJobQueueRunning,
            tblJobQueuePending, tblJobQueueFailed, tblJobQueueDeposited, tblJobQueueComplete, mnuFileFavourites,
            lstProducers, lstMaterialFlow);
    LOG.debug("setupScreen, handlers added");
    checkButtons();
    setCMSDetails();
    setHotKeyVisibility();
    depositPresenter.checkForInitialLoadScreenSizes(theFormControl, splitAddIE, SPLIT_IE_ATTR, splitMain,
            SPLIT_MAIN_ATTR, splitMainDetail, SPLIT_MAIN_DETAIL_ATTR, splitMainRight, SPLIT_MAIN_RIGHT_ATTR);
    final Action updateDividersAction = new AbstractAction() {
        public void actionPerformed(final ActionEvent e) {
            Timer t = (Timer) e.getSource();
            t.stop();
            splitAddIE.setDividerLocation(theFormControl.getExtra(SPLIT_IE_ATTR, 175));
            splitMain.setDividerLocation(theFormControl.getExtra(SPLIT_MAIN_ATTR, 200));
            splitMainDetail.setDividerLocation(theFormControl.getExtra(SPLIT_MAIN_DETAIL_ATTR, 200));
            splitMainRight.setDividerLocation(theFormControl.getExtra(SPLIT_MAIN_RIGHT_ATTR, 200));
            splitMain.repaint();
            splitMainDetail.repaint();
            splitMainRight.repaint();
            TableColumn col = tblDetail.getColumnModel().getColumn(0);
            col.setPreferredWidth(theFormControl.getExtra(META_DATA_COL_1_ATTR, 200));
            col = tblDetail.getColumnModel().getColumn(1);
            col.setPreferredWidth(theFormControl.getExtra(META_DATA_COL_2_ATTR, 200));

            MultiSplitLayout layout = mspJobQueue.getMultiSplitLayout();
            layout.setFloatingDividers(false);
            MultiSplitLayout.Split model = (MultiSplitLayout.Split) layout.getModel();
            MultiSplitLayout.Divider divider = (MultiSplitLayout.Divider) model.getChildren().get(1);
            Rectangle bounds = divider.getBounds();
            int top = theFormControl.getExtra(JOB_QUEUE_DIVIDER_1_ATTR, bounds.y);
            bounds.y = top;
            divider.setBounds(bounds);
            theOldHeight1 = top;

            divider = (MultiSplitLayout.Divider) model.getChildren().get(3);
            bounds = divider.getBounds();
            top = theFormControl.getExtra(JOB_QUEUE_DIVIDER_2_ATTR, bounds.y);
            bounds.y = top;
            divider.setBounds(bounds);
            theOldHeight2 = top;

            divider = (MultiSplitLayout.Divider) model.getChildren().get(5);
            bounds = divider.getBounds();
            top = theFormControl.getExtra(JOB_QUEUE_DIVIDER_3_ATTR, bounds.y);
            bounds.y = top;
            divider.setBounds(bounds);
            theOldHeight3 = top;

            divider = (MultiSplitLayout.Divider) model.getChildren().get(7);
            bounds = divider.getBounds();
            top = theFormControl.getExtra(JOB_QUEUE_DIVIDER_4_ATTR, bounds.y);
            bounds.y = top;
            divider.setBounds(bounds);
            theOldHeight4 = top;
        }
    };
    new Timer(200, updateDividersAction).start();
    final PersonalSettings personalSettings = theAppProperties.getApplicationData().getPersonalSettings();
    theStandardFont = personalSettings.getStandardFont();
    final SortBy sortBy = personalSettings.getSortFilesBy();
    for (int i = 0; i < cmbSortBy.getItemCount(); i++) {
        final SortBy item = (SortBy) cmbSortBy.getItemAt(i);
        if (item.equals(sortBy)) {
            cmbSortBy.setSelectedIndex(i);
            break;
        }
    }
    setJobQueuePanes();
    LOG.debug("setupScreen, end");
    addHotKeyListener(this);
}

From source file:dmh.kuebiko.view.NoteStackFrame.java

/**
 * Perform additional setup to the frame. This is separate from the
 * initialize() method so that the GUI builder doesn't mess with it.
 *///from   www .j  a  va2s .  c  om
private void additionalSetup() {
    mode = Mode.SEARCH;

    setFocusTraversalPolicy(new CustomFocusTraversalPolicy(searchText, notePanel));

    // Search Text Field.
    AutoCompleteDecorator.decorate(searchText, noteMngr.getNoteTitles(), false);
    searchText.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "clear");
    searchText.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
            onSearchTextChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            onSearchTextChanged();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            onSearchTextChanged();
        }
    });
    searchText.getActionMap().put("clear", new AbstractAction() {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            searchText.setText(null);
        }
    });

    searchText.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            setModeToSearch();
            searchText.selectAll();
        }

        @Override
        public void focusLost(FocusEvent e) {
            noteTable.selectNote(searchText.getText());
        }
    });
    searchText.addActionListener(actionMngr.getAction(NewNoteAction.class));

    // Note Table.
    noteTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent event) {
            if (event.getValueIsAdjusting()) {
                return;
            }
            final Note selectedNote = noteTable.getSelectedNote();

            if (selectedNote == null) {
                setModeToSearch();
            } else {
                setModeToEdit();
                notePanel.setNote(selectedNote);
                searchText.setText(selectedNote.getTitle());
            }
        }
    });
}

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

@Override
protected final void setupKeyBindingsHook(final JTextPane editor) {
    // 'Rename' action 
    addKeyBinding(editor, KeyStroke.getKeyStroke(KeyEvent.VK_R, Event.ALT_MASK | Event.SHIFT_MASK),
            new AbstractAction() {
                @Override/*from  w ww  .  j  a  v  a 2  s .c o m*/
                public void actionPerformed(ActionEvent e) {
                    maybeRenameLabel(editor.getCaretPosition());
                }
            });
}

From source file:nz.govt.natlib.ndha.manualdeposit.jobmanagement.JobQueueManagement.java

private void checkSipStatus() {
    LOG.debug("Start checkSipStatus");
    for (int i = jobQueueDeposited.size() - 1; i >= 0; i--) {
        final UploadJob job = jobQueueDeposited.get(i);
        job.checkSipStatus();//  www  . ja v  a2s .  co m
    }
    for (int i = jobQueueAwaitingCleanup.size() - 1; i >= 0; i--) {
        final UploadJob job = jobQueueAwaitingCleanup.get(i);
        job.checkForCleanup();
    }
    final Action checkSipStatusAction = new AbstractAction() {
        private static final long serialVersionUID = -8315654343127184873L;

        public void actionPerformed(final ActionEvent e) {
            Timer t = (Timer) e.getSource();
            t.stop();
            checkSipStatus();
        }
    };
    new Timer(theAppProperties.getApplicationData().getSipStatusRefreshInterval(), checkSipStatusAction)
            .start();
    LOG.debug("End checkSipStatus");
}

From source file:org.rdv.ui.ExportVideoDialog.java

private void initComponents() {

    JPanel container = new JPanel();
    setContentPane(container);/*from www.  j  a  v a  2s. c  om*/

    InputMap inputMap = container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actionMap = container.getActionMap();

    container.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.weighty = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.ipadx = 0;
    c.ipady = 0;

    JLabel headerLabel = new JLabel("Select the time range and video channels to export.");
    headerLabel.setBackground(Color.white);
    headerLabel.setOpaque(true);
    headerLabel.setBorder(
            BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray),
                    BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new java.awt.Insets(0, 0, 0, 0);
    container.add(headerLabel, c);

    JPanel timeButtonPanel = new JPanel();
    timeButtonPanel.setLayout(new BorderLayout());

    MouseListener hoverMouseListener = new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            e.getComponent().setForeground(Color.red);
        }

        public void mouseExited(MouseEvent e) {
            e.getComponent().setForeground(Color.blue);
        }
    };

    startTimeButton = new JButton();
    startTimeButton.setBorder(null);
    startTimeButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    startTimeButton.setForeground(Color.blue);
    startTimeButton.addMouseListener(hoverMouseListener);
    startTimeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            double startTime = DateTimeDialog.showDialog(ExportVideoDialog.this, timeSlider.getStart(),
                    timeSlider.getMinimum(), timeSlider.getEnd());
            if (startTime >= 0) {
                timeSlider.setStart(startTime);
            }
        }
    });
    timeButtonPanel.add(startTimeButton, BorderLayout.WEST);

    durationLabel = new JLabel();
    durationLabel.setHorizontalAlignment(JLabel.CENTER);
    timeButtonPanel.add(durationLabel, BorderLayout.CENTER);

    endTimeButton = new JButton();
    endTimeButton.setBorder(null);
    endTimeButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    endTimeButton.setForeground(Color.blue);
    endTimeButton.addMouseListener(hoverMouseListener);
    endTimeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            double endTime = DateTimeDialog.showDialog(ExportVideoDialog.this, timeSlider.getEnd(),
                    timeSlider.getStart(), timeSlider.getMaximum());
            if (endTime >= 0) {
                timeSlider.setEnd(endTime);
            }
        }
    });
    timeButtonPanel.add(endTimeButton, BorderLayout.EAST);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new java.awt.Insets(10, 10, 10, 10);
    container.add(timeButtonPanel, c);

    timeSlider = new TimeSlider();
    timeSlider.setValueChangeable(false);
    timeSlider.setValueVisible(false);
    timeSlider.addTimeAdjustmentListener(new TimeAdjustmentListener() {
        public void timeChanged(TimeEvent event) {
        }

        public void rangeChanged(TimeEvent event) {
            updateTimeRangeLabel();
        }

        public void boundsChanged(TimeEvent event) {
        }
    });
    updateTimeRangeLabel();
    updateTimeBounds();

    List<EventMarker> markers = rbnb.getMarkerManager().getMarkers();
    for (EventMarker marker : markers) {
        timeSlider.addMarker(marker);
    }

    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new java.awt.Insets(0, 10, 10, 10);
    container.add(timeSlider, c);

    JLabel numericHeaderLabel = new JLabel("Video Channels:");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.gridx = 0;
    c.gridy = 3;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new java.awt.Insets(0, 10, 10, 10);
    container.add(numericHeaderLabel, c);

    videoChannelList = new JList(videoChannelModel);
    videoChannelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    videoChannelList.setCellRenderer(new CheckListRenderer());
    videoChannelList.setVisibleRowCount(10);
    videoChannelList.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            int index = videoChannelList.locationToIndex(e.getPoint());
            ExportChannel item = (ExportChannel) videoChannelList.getModel().getElementAt(index);
            item.setSelected(!item.isSelected());
            Rectangle rect = videoChannelList.getCellBounds(index, index);
            videoChannelList.repaint(rect);

            updateTimeBounds();
        }
    });
    JScrollPane scrollPane = new JScrollPane(videoChannelList);
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 0;
    c.weighty = 1;
    c.gridx = 0;
    c.gridy = 4;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.anchor = GridBagConstraints.NORTHEAST;
    c.insets = new java.awt.Insets(0, 10, 10, 10);
    container.add(scrollPane, c);

    c.fill = GridBagConstraints.NONE;
    c.weightx = 0;
    c.weighty = 0;
    c.gridx = 0;
    c.gridy = 5;
    c.gridwidth = 1;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.insets = new java.awt.Insets(0, 10, 10, 5);
    container.add(new JLabel("Choose Directory: "), c);

    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;
    c.gridx = 1;
    c.gridy = 5;
    c.gridwidth = 1;
    c.anchor = GridBagConstraints.NORTHWEST;
    directoryTextField = new JTextField(20);
    c.insets = new java.awt.Insets(0, 0, 10, 5);
    container.add(directoryTextField, c);

    directoryTextField.setText(UIUtilities.getCurrentDirectory().getAbsolutePath());
    directoryButton = new JButton("Browse");
    directoryButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            File selectedDirectory = UIUtilities.getDirectory("Select export directory");
            if (selectedDirectory != null) {
                directoryTextField.setText(selectedDirectory.getAbsolutePath());
            }
        }
    });
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0;
    c.gridx = 2;
    c.gridy = 5;
    c.gridwidth = 1;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.insets = new java.awt.Insets(0, 0, 10, 10);
    container.add(directoryButton, c);

    exportProgressBar = new JProgressBar(0, 100000);
    exportProgressBar.setStringPainted(true);
    exportProgressBar.setValue(0);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.5;
    c.gridx = 0;
    c.gridy = 6;
    c.gridwidth = GridBagConstraints.REMAINDER;
    ;
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new java.awt.Insets(0, 10, 10, 10);
    container.add(exportProgressBar, c);

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    Action exportAction = new AbstractAction() {
        /** serialization version identifier */
        private static final long serialVersionUID = 1547500154252213911L;

        public void actionPerformed(ActionEvent e) {
            exportVideo();
        }
    };
    exportAction.putValue(Action.NAME, "Export");
    inputMap.put(KeyStroke.getKeyStroke("ENTER"), "export");
    actionMap.put("export", exportAction);
    exportButton = new JButton(exportAction);
    panel.add(exportButton);

    Action cancelAction = new AbstractAction() {
        /** serialization version identifier */
        private static final long serialVersionUID = -7440298547807878651L;

        public void actionPerformed(ActionEvent e) {
            cancel();
        }
    };
    cancelAction.putValue(Action.NAME, "Cancel");
    inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), "cancel");
    actionMap.put("cancel", cancelAction);
    cancelButton = new JButton(cancelAction);
    panel.add(cancelButton);

    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.5;
    c.gridx = 0;
    c.gridy = 7;
    c.gridwidth = GridBagConstraints.REMAINDER;
    ;
    c.anchor = GridBagConstraints.LINE_END;
    c.insets = new java.awt.Insets(0, 0, 10, 5);
    container.add(panel, c);

    pack();
    if (getWidth() < 600) {
        setSize(600, getHeight());
    }

    directoryTextField.requestFocusInWindow();

    setLocationByPlatform(true);
    setVisible(true);
}

From source file:net.sf.jabref.openoffice.StyleSelectDialog.java

private void init(String inSelection) {
    this.initSelection = inSelection;

    ButtonGroup bg = new ButtonGroup();
    bg.add(useDefaultAuthoryear);// w  ww. j a v a2 s.  c  o m
    bg.add(useDefaultNumerical);
    bg.add(chooseDirectly);
    bg.add(setDirectory);
    if (Globals.prefs.getBoolean(JabRefPreferences.OO_USE_DEFAULT_AUTHORYEAR_STYLE)) {
        useDefaultAuthoryear.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.OO_USE_DEFAULT_NUMERICAL_STYLE)) {
        useDefaultNumerical.setSelected(true);
    } else {
        if (Globals.prefs.getBoolean(JabRefPreferences.OO_CHOOSE_STYLE_DIRECTLY)) {
            chooseDirectly.setSelected(true);
        } else {
            setDirectory.setSelected(true);
        }
    }

    directFile.setText(Globals.prefs.get(JabRefPreferences.OO_DIRECT_FILE));
    styleDir.setText(Globals.prefs.get(JabRefPreferences.OO_STYLE_DIRECTORY));
    directFile.setEditable(false);
    styleDir.setEditable(false);

    popup.add(edit);

    BrowseAction dfBrowse = BrowseAction.buildForFile(directFile, directFile);
    browseDirectFile.addActionListener(dfBrowse);

    BrowseAction sdBrowse = BrowseAction.buildForDir(styleDir, setDirectory);
    browseStyleDir.addActionListener(sdBrowse);

    showDefaultAuthoryearStyle.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            displayDefaultStyle(true);
        }
    });
    showDefaultNumericalStyle.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            displayDefaultStyle(false);
        }
    });
    // Add action listener to "Edit" menu item, which is supposed to open the style file in an external editor:
    edit.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            int i = table.getSelectedRow();
            if (i == -1) {
                return;
            }
            ExternalFileType type = ExternalFileTypes.getInstance().getExternalFileTypeByExt("jstyle");
            String link = tableModel.getElementAt(i).getFile().getPath();
            try {
                if (type == null) {
                    JabRefDesktop.openExternalFileUnknown(frame, new BibEntry(), new MetaData(), link,
                            new UnknownExternalFileType("jstyle"));
                } else {
                    JabRefDesktop.openExternalFileAnyFormat(new MetaData(), link, type);
                }
            } catch (IOException e) {
                LOGGER.warn("Problem open style file editor", e);
            }
        }
    });

    diag = new JDialog(frame, Localization.lang("Styles"), true);

    styles = new BasicEventList<>();
    EventList<OOBibStyle> sortedStyles = new SortedList<>(styles);

    // Create a preview panel for previewing styles:
    preview = new PreviewPanel(null, new MetaData(), "");
    // Use the test entry from the Preview settings tab in Preferences:
    preview.setEntry(prevEntry);

    tableModel = (DefaultEventTableModel<OOBibStyle>) GlazedListsSwing
            .eventTableModelWithThreadProxyList(sortedStyles, new StyleTableFormat());
    table = new JTable(tableModel);
    TableColumnModel cm = table.getColumnModel();
    cm.getColumn(0).setPreferredWidth(100);
    cm.getColumn(1).setPreferredWidth(200);
    cm.getColumn(2).setPreferredWidth(80);
    selectionModel = (DefaultEventSelectionModel<OOBibStyle>) GlazedListsSwing
            .eventSelectionModelWithThreadProxyList(sortedStyles);
    table.setSelectionModel(selectionModel);
    table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent mouseEvent) {
            if (mouseEvent.isPopupTrigger()) {
                tablePopup(mouseEvent);
            }
        }

        @Override
        public void mouseReleased(MouseEvent mouseEvent) {
            if (mouseEvent.isPopupTrigger()) {
                tablePopup(mouseEvent);
            }
        }
    });

    selectionModel.getSelected().addListEventListener(new EntrySelectionListener());

    styleDir.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            readStyles();
            setDirectory.setSelected(true);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            readStyles();
            setDirectory.setSelected(true);
        }

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            readStyles();
            setDirectory.setSelected(true);
        }
    });
    directFile.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            chooseDirectly.setSelected(true);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            chooseDirectly.setSelected(true);
        }

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            chooseDirectly.setSelected(true);
        }
    });

    contentPane.setTopComponent(new JScrollPane(table));
    contentPane.setBottomComponent(preview);

    readStyles();

    DefaultFormBuilder b = new DefaultFormBuilder(
            new FormLayout("fill:pref,4dlu,fill:150dlu,4dlu,fill:pref", ""));
    b.append(useDefaultAuthoryear, 3);
    b.append(showDefaultAuthoryearStyle);
    b.nextLine();
    b.append(useDefaultNumerical, 3);
    b.append(showDefaultNumericalStyle);
    b.nextLine();
    b.append(chooseDirectly);
    b.append(directFile);
    b.append(browseDirectFile);
    b.nextLine();
    b.append(setDirectory);
    b.append(styleDir);
    b.append(browseStyleDir);
    b.nextLine();
    DefaultFormBuilder b2 = new DefaultFormBuilder(
            new FormLayout("fill:1dlu:grow", "fill:pref, fill:pref, fill:270dlu:grow"));

    b2.nextLine();
    b2.append(new JLabel("<html>"
            + Localization.lang("This is the list of available styles. Select the one you want to use.")
            + "</html>"));
    b2.nextLine();
    b2.append(contentPane);
    b.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    b2.getPanel().setBorder(BorderFactory.createEmptyBorder(15, 5, 5, 5));
    diag.add(b.getPanel(), BorderLayout.NORTH);
    diag.add(b2.getPanel(), BorderLayout.CENTER);

    AbstractAction okListener = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (!useDefaultAuthoryear.isSelected() && !useDefaultNumerical.isSelected()) {
                if (chooseDirectly.isSelected()) {
                    File f = new File(directFile.getText());
                    if (!f.exists()) {
                        JOptionPane.showMessageDialog(diag,
                                Localization.lang(
                                        "You must select either a valid style file, or use a default style."),
                                Localization.lang("Style selection"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else {
                    if ((table.getRowCount() == 0) || (table.getSelectedRowCount() == 0)) {
                        JOptionPane.showMessageDialog(diag,
                                Localization.lang(
                                        "You must select either a valid style file, or use a default style."),
                                Localization.lang("Style selection"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                }
            }
            okPressed = true;
            storeSettings();
            diag.dispose();
        }
    };
    ok.addActionListener(okListener);

    Action cancelListener = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent event) {
            diag.dispose();
        }
    };
    cancel.addActionListener(cancelListener);

    ButtonBarBuilder bb = new ButtonBarBuilder();
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(cancel);
    bb.addGlue();
    bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    diag.add(bb.getPanel(), BorderLayout.SOUTH);

    ActionMap am = bb.getPanel().getActionMap();
    InputMap im = bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", cancelListener);
    im.put(KeyStroke.getKeyStroke("ENTER"), "enterOk");
    am.put("enterOk", okListener);

    diag.pack();
    diag.setLocationRelativeTo(frame);
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            contentPane.setDividerLocation(contentPane.getSize().height - 150);
        }
    });

}