Example usage for com.jgoodies.forms.layout FormLayout FormLayout

List of usage examples for com.jgoodies.forms.layout FormLayout FormLayout

Introduction

In this page you can find the example usage for com.jgoodies.forms.layout FormLayout FormLayout.

Prototype

public FormLayout(ColumnSpec[] colSpecs, RowSpec[] rowSpecs) 

Source Link

Document

Constructs a FormLayout using the given column and row specifications.

Usage

From source file:ca.sqlpower.swingui.ModalDialogListUserPrompter.java

License:Open Source License

public ModalDialogListUserPrompter(JFrame parentFrame, String question, List<T> responses, T defaultResponse) {
    this.parentFrame = parentFrame;
    this.defaultResponse = defaultResponse;
    applyToAll = new JCheckBox(Messages.getString("ModalDialogUserPrompter.applyToAllOption")); //$NON-NLS-1$

    confirmDialog = new JDialog(parentFrame);

    // FIXME the title needs to be configurable and/or set itself based on prompt type
    confirmDialog.setTitle(""); //$NON-NLS-1$

    // this is just filled with the message pattern template to help with sizing
    questionField = new JTextArea(question);
    questionField.setEditable(false);//  w  ww. j  a  v a2s.  c  o m
    questionField.setBackground(null);

    questionFormat = new MessageFormat(question);

    JPanel confirmPanel = new JPanel();
    FormLayout formLayout = new FormLayout("pref:grow" //$NON-NLS-1$
            , ""); //$NON-NLS-1$

    optionBox = new JComboBox();
    for (T item : responses) {
        optionBox.addItem(item);
    }

    optionBox.setSelectedItem(defaultResponse);
    DefaultFormBuilder builder = new DefaultFormBuilder(formLayout, confirmPanel);
    builder.setDefaultDialogBorder();

    builder.append(questionField);

    builder.nextLine();
    builder.append(optionBox);

    builder.nextLine();
    ButtonBarBuilder buttonBar = new ButtonBarBuilder();
    buttonBar.addGlue();
    JButton okButton = new JButton();
    okButton.setText("Ok");
    buttonBar.addGridded(okButton);
    buttonBar.addGlue();

    okButton.addActionListener(new ActionListener() {
        @SuppressWarnings("unchecked")
        public void actionPerformed(ActionEvent e) {
            responseButton = UserPromptResponse.OK;
            response = (T) optionBox.getSelectedItem();
            confirmDialog.dispose();
        }
    });
    builder.append(""); //$NON-NLS-1$
    builder.append(buttonBar.getPanel());
    builder.nextLine();

    builder.append(""); //$NON-NLS-1$
    builder.append(applyToAll);

    okButton.requestFocusInWindow();

    confirmDialog.setModal(true);
    confirmDialog.add(builder.getPanel());
}

From source file:ca.sqlpower.swingui.query.SQLQueryUIComponents.java

License:Open Source License

/**
 * Builds the UI of the {@link SQLQueryUIComponents}. If you just want an
 * easy way to build a full-featured query UI and don't want to customize
 * its internals, you have come to the right place. This also allows a SQL
 * string to initialize the query UI with.
 * /*from   w w  w  .j  a  va 2 s  .com*/
 * @param swRegistry
 *            The registry with which all background tasks will be
 *            registered. This argument must not be null.
 * @param dsCollection
 *            The collection of data sources that will be available for
 *            querying from the UI. This argument must not be null.
 * 
 * @param ds
 *            The data source that the initial query will be executed on.
 *            This data source must be contained in the dsCollection and not
 *            null for the query to be executed. If the data source is null
 *            then the query will not be executed.
 * 
 * @param initialSQL
 *            The string that will be executed immediately when the query
 *            tool is shown. If this is null then no query will be executed.
 */
public static JComponent createQueryPanel(SwingWorkerRegistry swRegistry, DataSourceCollection dsCollection,
        SQLDatabaseMapping mapping, Window owner, SQLDatabase db, String initialSQL) {

    JPanel defaultQueryPanel = new JPanel();
    SQLQueryUIComponents queryParts = new SQLQueryUIComponents(swRegistry, dsCollection, mapping,
            defaultQueryPanel);
    queryParts.addWindowListener(owner);
    JToolBar toolbar = new JToolBar();
    toolbar.setFloatable(false);
    toolbar.add(queryParts.getPrevQueryButton());
    toolbar.add(queryParts.getNextQueryButton());
    toolbar.addSeparator();
    toolbar.add(queryParts.getExecuteButton());
    toolbar.add(queryParts.getStopButton());
    toolbar.add(queryParts.getClearButton());
    toolbar.addSeparator();
    toolbar.add(queryParts.getAutoCommitToggleButton());
    toolbar.add(queryParts.getCommitButton());
    toolbar.add(queryParts.getRollbackButton());
    toolbar.addSeparator();
    toolbar.add(queryParts.getUndoButton());
    toolbar.add(queryParts.getRedoButton());

    FormLayout textAreaLayout = new FormLayout("pref:grow, 10dlu, pref, 10dlu, pref, 10dlu, pref",
            "pref, pref, fill:max(100dlu;pref):grow");
    DefaultFormBuilder textAreaBuilder = new DefaultFormBuilder(textAreaLayout, defaultQueryPanel);
    textAreaBuilder.setDefaultDialogBorder();
    textAreaBuilder.append(toolbar, 7);
    textAreaBuilder.nextLine();
    textAreaBuilder.append(queryParts.getDatabaseComboBox());
    textAreaBuilder.append(queryParts.getDbcsManagerButton());
    textAreaBuilder.append(Messages.getString("SQLQuery.rowLimit"));
    JSpinner rowlimitSpinner = queryParts.getRowLimitSpinner();
    rowlimitSpinner.setValue(new Integer(1000));
    textAreaBuilder.append(rowlimitSpinner);
    textAreaBuilder.nextLine();
    textAreaBuilder.append(new RTextScrollPane(queryParts.getQueryArea(), true), 7);

    JSplitPane queryPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

    queryPane.add(defaultQueryPanel, JSplitPane.TOP);

    queryPane.add(queryParts.getResultTabPane(), JSplitPane.BOTTOM);

    if (db != null && initialSQL != null && dsCollection.getConnections().contains(db.getDataSource())) {
        queryParts.getDatabaseComboBox().setSelectedItem(db.getDataSource());
        queryParts.getQueryArea().setText(initialSQL);
        queryParts.executeQuery(initialSQL);
    }

    return queryPane;

}

From source file:ca.sqlpower.swingui.query.SQLQueryUIComponents.java

License:Open Source License

/**
 * Creates all of the JTables for the result tab and adds them to the result tab.
 * @throws SQLException /*from   w  ww . ja va2s. c  o  m*/
 */
private synchronized void createResultSetTables(List<CachedRowSet> resultSets, StatementExecutor executor)
        throws SQLException {
    clearResultTables(true);
    for (StreamingRowSetListener rowSetListener : rowSetListeners) {
        rowSetListener.disconnect();
    }
    rowSetListeners.clear();

    searchDocument = new DefaultStyledDocument();
    for (CachedRowSet rs : resultSets) {
        final JTable tempTable;
        FormLayout tableAreaLayout = new FormLayout("pref, 3dlu, pref:grow", "pref, fill:min(pref;50dlu):grow");
        DefaultFormBuilder tableAreaBuilder = new DefaultFormBuilder(tableAreaLayout);

        if (showSearchOnResults) {
            JLabel searchLabel = new JLabel(ICON);
            searchLabel.setToolTipText("Search");
            JTextField tableFilterTextField = new JTextField(searchDocument, null, 0);
            tableAreaBuilder.append(searchLabel, tableFilterTextField);
        }
        ResultSetTableModel model = new ResultSetTableModel(rs);
        StreamingRowSetListener rowSetListener = new StreamingRowSetListener(rs, model);
        rs.addRowSetListener(rowSetListener);
        rowSetListeners.add(rowSetListener);

        tempTable = new FancyExportableJTable(model, searchDocument);
        final TableModelListener tableListener = new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                tempTable.createDefaultColumnsFromModel();
            }
        };
        model.addTableModelListener(tableListener);

        // Allow users to select a single table cell.
        tempTable.setCellSelectionEnabled(true);

        tableAreaBuilder.nextLine();
        JScrollPane tableScrollPane = new JScrollPane(tempTable);
        tableScrollPane.setPreferredSize(new Dimension((int) tableScrollPane.getPreferredSize().getWidth(), 0));
        resultJTableScrollPanes.put(tempTable, tableScrollPane);
        tableAreaBuilder.append(tableScrollPane, 3);

        resultJTables.add((JTable) tempTable);
        tableToSQLMap.put(((JTable) tempTable), executor.getStatement());
        JPanel tempResultPanel = tableAreaBuilder.getPanel();
        resultTabPane.add(Messages.getString("SQLQuery.result"), tempResultPanel);
        resultTabPane.setSelectedIndex(1);

    }
    for (JTable table : resultJTables) {
        for (TableChangeListener l : tableListeners) {
            l.tableAdded(new TableChangeEvent(this, table));
        }
    }
}

From source file:ca.sqlpower.util.HTMLUserPrompter.java

License:Open Source License

/**
 * Creates a new user prompter that uses a dialog to prompt the user. The
 * question message is displayed in a {@link JEditorPane} so that it can be
 * displayed using styles via HTML. A {@link HyperlinkListener} can be
 * attached to this prompt to open hyperlinks.
 *///from   ww w .j a  va 2s  . c o  m
public HTMLUserPrompter(UserPromptOptions optionType, UserPromptResponse defaultResponseType, JFrame owner,
        String questionMessage, boolean modal, HyperlinkListener hyperlinkListener, String... buttonNames) {
    if (optionType.getButtonCount() != buttonNames.length) {
        throw new IllegalStateException(
                "Expecting " + optionType.getButtonCount() + " arguments for the optionType " + optionType
                        + "Received only " + buttonNames.length + "arguments\n" + Arrays.toString(buttonNames));
    }
    this.defaultResponseType = defaultResponseType;
    this.owner = owner;
    applyToAll = new JCheckBox(Messages.getString("ModalDialogUserPrompter.applyToAllOption")); //$NON-NLS-1$

    confirmDialog = new JDialog(owner);

    // FIXME the title needs to be configurable and/or set itself based on prompt type
    confirmDialog.setTitle(""); //$NON-NLS-1$

    // this is just filled with the message pattern template to help with sizing
    questionField = new JEditorPane();
    questionField.setEditorKit(new HTMLEditorKit());
    questionField.setText(questionMessage);
    questionField.setEditable(false);
    questionField.setBackground(null);
    if (hyperlinkListener != null) {
        questionField.addHyperlinkListener(hyperlinkListener);
    }

    JPanel confirmPanel = new JPanel();
    FormLayout formLayout = new FormLayout("10dlu, 2dlu, pref:grow, 2dlu, 10dlu" //$NON-NLS-1$
            , ""); //$NON-NLS-1$
    DefaultFormBuilder builder = new DefaultFormBuilder(formLayout, confirmPanel);
    builder.setDefaultDialogBorder();

    builder.nextColumn(2);
    builder.append(questionField);
    builder.nextLine();

    builder.appendParagraphGapRow();
    builder.nextLine();

    ButtonBarBuilder buttonBar = new ButtonBarBuilder();
    buttonBar.addGlue();
    JButton okButton = new JButton();
    if (optionType == UserPromptOptions.OK_NEW_NOTOK_CANCEL || optionType == UserPromptOptions.OK_NOTOK_CANCEL
            || optionType == UserPromptOptions.OK_NEW_CANCEL || optionType == UserPromptOptions.OK_CANCEL
            || optionType == UserPromptOptions.OK) {
        okButton.setText(buttonNames[0]);
        buttonBar.addGridded(okButton);
    }
    JButton notOkButton = new JButton();
    if (optionType == UserPromptOptions.OK_NEW_NOTOK_CANCEL
            || optionType == UserPromptOptions.OK_NOTOK_CANCEL) {
        buttonBar.addRelatedGap();
        notOkButton
                .setText((optionType == UserPromptOptions.OK_NOTOK_CANCEL) ? buttonNames[1] : buttonNames[2]);
        buttonBar.addGridded(notOkButton);
    }
    JButton cancelButton = new JButton();
    if (optionType == UserPromptOptions.OK_NEW_NOTOK_CANCEL || optionType == UserPromptOptions.OK_NOTOK_CANCEL
            || optionType == UserPromptOptions.OK_NEW_CANCEL || optionType == UserPromptOptions.OK_CANCEL) {
        buttonBar.addRelatedGap();
        cancelButton.setText(buttonNames[buttonNames.length - 1]);
        buttonBar.addGridded(cancelButton);
    }
    buttonBar.addGlue();

    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            response = UserPromptResponse.OK;
            confirmDialog.dispose();
        }
    });
    notOkButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            response = UserPromptResponse.NOT_OK;
            confirmDialog.dispose();
        }
    });
    cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            response = UserPromptResponse.CANCEL;
            confirmDialog.dispose();
        }
    });
    builder.append(""); //$NON-NLS-1$
    builder.append(buttonBar.getPanel());
    builder.nextLine();

    builder.append(""); //$NON-NLS-1$
    builder.append(applyToAll);

    switch (defaultResponseType) {
    case OK:
        okButton.requestFocusInWindow();
        break;
    case NOT_OK:
        notOkButton.requestFocusInWindow();
        break;
    case CANCEL:
        cancelButton.requestFocusInWindow();
        break;
    default:
        throw new UnsupportedOperationException(
                "Default response type : " + defaultResponseType + " is not known");
    }

    confirmDialog.setModal(modal);
    confirmDialog.add(builder.getPanel());
}

From source file:ca.sqlpower.wabit.swingui.enterprise.ServerInfoManager.java

License:Open Source License

/**
 * Creates a panel that displays the currently configured server
 * connections. New connections can be added from this panel and existing
 * connections can be modified or removed.
 * //from  w w  w.j  a v  a 2 s  .  co  m
 * @param m_context
 *            A Wabit context that contains server connection information.
 * @param m_dialogOwner
 *            A component that will be used as the dialog owner for other
 *            panels.
 * @param closeAction
 *            An action that will properly close the object displaying the
 *            panel.
 */
public ServerInfoManager(WabitSessionContext m_context, Component m_dialogOwner, final Runnable closeAction) {
    this.context = m_context;
    this.dialogOwner = m_dialogOwner;
    DefaultFormBuilder builder = new DefaultFormBuilder(
            new FormLayout("pref:grow, 5dlu, pref", "pref, pref, pref"));

    serverInfos = new JList(new DefaultListModel());
    serverInfos.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
                editSelectedServer();
            }
        }

    });
    JScrollPane scrollPane = new JScrollPane(serverInfos);
    scrollPane.setPreferredSize(new Dimension(400, 300));

    this.connectButton = new JButton("Connect");
    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            SPServerInfo selectedItem = (SPServerInfo) serverInfos.getSelectedValue();

            Window dialogParent;
            if (dialogOwner instanceof Window) {
                dialogParent = (Window) dialogOwner;
            } else {
                dialogParent = SwingUtilities.getWindowAncestor(dialogOwner);
            }

            if (selectedItem != null) {
                LogInToServerAction action = new LogInToServerAction(dialogParent, selectedItem, context);
                action.actionPerformed(e);
            }
        }
    });

    // Build the GUI
    refreshInfoList();
    CellConstraints cc = new CellConstraints();
    builder.add(new JLabel("Available Server Connections:"), cc.xyw(1, 1, 3));
    builder.nextLine();
    builder.add(scrollPane, cc.xywh(1, 2, 1, 2));

    DefaultFormBuilder buttonBarBuilder = new DefaultFormBuilder(new FormLayout("pref"));
    buttonBarBuilder.append(new JButton(addAction));
    buttonBarBuilder.append(new JButton(editAction));
    buttonBarBuilder.append(new JButton(removeAction));
    buttonBarBuilder.append(connectButton);
    buttonBarBuilder.append(new JButton(new AbstractAction("Close") {
        public void actionPerformed(ActionEvent arg0) {
            closeAction.run();
        }
    }));
    builder.add(buttonBarBuilder.getPanel(), cc.xy(3, 2));
    builder.setDefaultDialogBorder();
    panel = builder.getPanel();
}

From source file:ca.sqlpower.wabit.swingui.QueryPanel.java

License:Open Source License

public QueryPanel(WabitSwingSession session, QueryCache cache) {
    logger.debug("Constructing new QueryPanel@" + System.identityHashCode(this));
    this.session = session;
    context = (WabitSwingSessionContext) session.getContext();
    mainSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    queryCache = cache;//from   www .  java  2  s .  c  o  m

    queryCache.setResultSetListener(resultSetListener);
    queryCache.addResultSetProducerListener(rsProducerListener);

    final Action queryPenExecuteButtonAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            execute();
        }
    };
    queryPen = new QueryPen(queryPenExecuteButtonAction, queryCache);
    queryPen.setExecuteIcon((ImageIcon) WabitIcons.RUN_ICON_32);
    queryPen.getGlobalWhereText().setText(cache.getGlobalWhereClause());

    exportQueryAction = new ExportWabitObjectAction<QueryCache>(session, queryCache,
            WabitIcons.WABIT_FILE_ICON_16, "Export Query to Wabit file");

    queryUIComponents = new SQLQueryUIComponents(session,
            new SpecificDataSourceCollection<JDBCDataSource>(session.getWorkspace(), JDBCDataSource.class),
            context, mainSplitPane, queryCache);
    queryUIComponents.setRowLimitSpinner(context.getRowLimitSpinner());
    queryUIComponents.setShowSearchOnResults(false);
    queryController = new QueryController(queryCache, queryPen, queryUIComponents.getDatabaseComboBox(),
            queryUIComponents.getQueryArea(), queryPen.getZoomSlider());
    queryPen.setZoom(queryCache.getZoomLevel());
    reportComboBox = queryUIComponents.getDatabaseComboBox();

    cornerPanel = new JPanel();
    DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("pref", "pref, pref, pref"),
            cornerPanel);
    groupingLabel.setFont(new JTableHeader().getFont());

    //Resize grouping and having labels to the height of a combo box to be spaced properly
    //beside the headers in the results table. This is done by a listener as the components
    //aren't realized until they are displayed.
    reportComboBox.addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent e) {
            groupingLabel.setPreferredSize(new Dimension((int) groupingLabel.getPreferredSize().getWidth(),
                    reportComboBox.getHeight()));
            havingLabel.setPreferredSize(
                    new Dimension((int) havingLabel.getPreferredSize().getWidth(), reportComboBox.getHeight()));
        }
    });
    havingLabel.setFont(new JTableHeader().getFont());
    builder.append(groupingLabel);
    builder.append(havingLabel);
    builder.append(columnNameLabel);

    dragTree = new JTree() {
        public void expandPath(TreePath tp) {
            try {
                if (tp.getLastPathComponent() instanceof SQLObject) {
                    ((SQLObject) tp.getLastPathComponent()).populate();
                }
                super.expandPath(tp);
            } catch (Exception ex) {
                logger.warn("Unexpected exception while expanding path " + tp, ex); //$NON-NLS-1$
            }
        }

        @Override
        public void expandRow(int row) {
            if (getPathForRow(row).getLastPathComponent() instanceof SQLObject) {
                try {
                    ((SQLObject) getPathForRow(row).getLastPathComponent()).populate();
                } catch (SQLObjectException e) {
                    throw new RuntimeException(e);
                }
            }
            super.expandRow(row);
        }
    };
    dragTree.setRootVisible(false);
    rootNode = new CustomSQLObjectRoot();
    reportComboBox.addActionListener(new AbstractAction() {
        public void actionPerformed(ActionEvent event) {
            try {
                for (int i = rootNode.getChildren().size() - 1; i >= 0; i--) {
                    rootNode.removeChild(rootNode.getChildren().get(i));
                }
                if (reportComboBox.getSelectedItem() != null) {
                    // FIXME the session (or session context) should be maintaining a map of data
                    // sources to SQLDatabase instances. Each SQLDatabase instance has its own connection pool! 
                    rootNode.addChild(context.getDatabase((JDBCDataSource) reportComboBox.getSelectedItem()));
                    for (SQLObject child : rootNode.getChildren()) {
                        child.populate();
                    }
                    DBTreeModel tempTreeModel = new DBTreeModel(rootNode, dragTree);
                    dragTree.setModel(tempTreeModel);
                    dragTree.expandRow(0);
                    dragTree.setVisible(true);
                }
            } catch (SQLObjectException e) {
                throw new RuntimeException("Could not add DataSource to rootNode", e);
            } catch (ObjectDependentException e) {
                throw new RuntimeException(e);
            }

        }
    });
    if (session.getWorkspace().getDataSources().size() != 0) {
        if (queryCache.getDatabase() == null) {
            dragTree.setVisible(false);
            List<SPDataSource> dataSources = session.getWorkspace().getConnections();
            List<JDBCDataSource> availableDS = new ArrayList<JDBCDataSource>();
            for (SPDataSource ds : dataSources) {
                if (ds instanceof JDBCDataSource) {
                    availableDS.add((JDBCDataSource) ds);
                }
            }
            final JDBCDataSource startingDataSource;
            if (availableDS.size() > 0) {
                startingDataSource = (JDBCDataSource) availableDS.get(0);
            } else {
                startingDataSource = null;
            }

            SPSwingWorker databaseLazyLoad = new SPSwingWorker(session) {
                public void doStuff() throws Exception {
                    if (startingDataSource != null) {
                        //populate the database
                        context.getDatabase(startingDataSource);
                    }
                }

                public void cleanup() throws Exception {
                    if (reportComboBox.getSelectedItem() == null) {
                        reportComboBox.setSelectedItem(startingDataSource);
                        dragTree.setVisible(true);
                    }
                }
            };
            //populates some data in a separate thread to create an easier workflow
            //when a user creates a new query (bug 2054)
            if (startingDataSource != null) {
                databaseLazyLoad.run();
            }
        } else {
            reportComboBox.setSelectedItem((SPDataSource) queryCache.getDatabase().getDataSource());
            dragTree.setVisible(true);
        }
    } else {
        dragTree.setVisible(false);
    }

    dragTree.setCellRenderer(new DBTreeCellRenderer());
    DragSource ds = new DragSource();
    ds.createDefaultDragGestureRecognizer(dragTree, DnDConstants.ACTION_COPY, new DragGestureListener() {

        public void dragGestureRecognized(DragGestureEvent dge) {

            if (dragTree.getSelectionPaths() == null) {
                return;
            }
            ArrayList<SQLObject> list = new ArrayList<SQLObject>();
            for (TreePath path : dragTree.getSelectionPaths()) {
                Object selectedNode = path.getLastPathComponent();
                if (!(selectedNode instanceof SQLObject)) {
                    throw new IllegalStateException(
                            "DBTrees are not allowed to contain non SQLObjects. This tree contains a "
                                    + selectedNode.getClass());
                }
                list.add((SQLObject) selectedNode);
            }

            Transferable dndTransferable = new SQLObjectSelection(list);
            dge.getDragSource().startDrag(dge, null, dndTransferable, new DragSourceAdapter() {
                // no op 
            });

        }
    });

    queryUIComponents.addTableChangeListener(new TableChangeListener() {
        public void tableRemoved(TableChangeEvent e) {
            if (tableColumnModel != null) {
                Enumeration<TableColumn> enumeration = tableColumnModel.getColumns();
                while (enumeration.hasMoreElements()) {
                    enumeration.nextElement().removePropertyChangeListener(resizingColumnChangeListener);
                }
                e.getChangedTable().getTableHeader()
                        .removeMouseMotionListener(reorderSelectionByHeaderAutoScrollTable);
            }
        }

        public void tableAdded(final TableChangeEvent e) {

            logger.debug("Table added.");
            queryController.unlistenToCellRenderer();
            TableModelSortDecorator sortDecorator = null;
            final JTable table = e.getChangedTable();
            if (table instanceof FancyExportableJTable) {
                FancyExportableJTable fancyTable = (FancyExportableJTable) table;
                sortDecorator = fancyTable.getTableModelSortDecorator();
            }
            ComponentCellRenderer renderer = new ComponentCellRenderer(table, sortDecorator);
            table.getTableHeader().setDefaultRenderer(renderer);

            ListModel lm = new RowListModel(table);
            final JList rowHeader = new JList(lm);
            rowHeader.setFixedCellWidth(groupingLabel.getPreferredSize().width + 2);

            rowHeader.setCellRenderer(new RowHeaderRenderer(table));

            table.addPropertyChangeListener("rowHeight", new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent evt) {
                    rowHeader.setFixedCellHeight(table.getRowHeight());
                }
            });

            rowHeader.setFixedCellHeight(table.getRowHeight());

            ((JScrollPane) table.getParent().getParent()).setRowHeaderView(rowHeader);

            ((JScrollPane) table.getParent().getParent()).setCorner(JScrollPane.UPPER_LEFT_CORNER, cornerPanel);
            addGroupingTableHeaders();

            tableColumnModel = e.getChangedTable().getColumnModel();
            Enumeration<TableColumn> enumeration = tableColumnModel.getColumns();
            while (enumeration.hasMoreElements()) {
                enumeration.nextElement().addPropertyChangeListener(resizingColumnChangeListener);
            }
            table.getTableHeader().addMouseMotionListener(reorderSelectionByHeaderAutoScrollTable);

            //TODO: Add the new renderer to result sets on both tabs when a parser exists to go between them easier.
            if (queryPenAndTextTabPane.getSelectedComponent() != queryToolPanel) {
                queryController.listenToCellRenderer(renderer);
            }

            columnNameLabel.setIcon(null);

            searchField.setDocument(queryUIComponents.getSearchDocument());

        }
    });

    buildUI();

    /*
     * Default split pane size is 3/4-1/4 of the screen height or else
     * the results won't be visible and the user won't see them update
     */
    mainSplitPane.setDividerLocation(prefs.getInt(RESULTS_DIVIDER_LOCATON_KEY,
            (int) (session.getContext().getFrame().getHeight() * 3 / 4)));

}

From source file:ca.sqlpower.wabit.swingui.WorkspacePanel.java

License:Open Source License

/**
 * This will create the DBConnectionManager for the WorkspacePanel and other panels that need
 * to allow users to add a data source to the workspace. One other place this gets used is
 * the NewWorkspaceScreen where the user adds the first data source to a workspace.
 * @param session/*ww  w .  j a v  a 2  s  .com*/
 * @return
 */
public static DatabaseConnectionManager createDBConnectionManager(final WabitSwingSession session,
        Window owner) {
    final WabitSwingSessionContext context = (WabitSwingSessionContext) session.getContext();
    List<JComponent> componentList = new ArrayList<JComponent>();
    DefaultFormBuilder startPanel = new DefaultFormBuilder(new FormLayout("fill:pref", "pref, pref"));
    final JLabel startImageLabel = new JLabel(UP_START_ICON);
    startImageLabel.setFocusable(true);
    startPanel.add(startImageLabel);
    JLabel startTextLabel = new JLabel("Start");
    startTextLabel.setHorizontalAlignment(SwingConstants.CENTER);
    startPanel.nextLine();
    startPanel.add(startTextLabel);
    componentList.add(startPanel.getPanel());
    List<Class<? extends SPDataSource>> newDSTypes = new ArrayList<Class<? extends SPDataSource>>();
    newDSTypes.add(JDBCDataSource.class);
    newDSTypes.add(Olap4jDataSource.class);
    final DatabaseConnectionManager dbConnectionManager = new DatabaseConnectionManager(
            session.getDataSources(), new DefaultDataSourceDialogFactory(),
            new DefaultDataSourceTypeDialogFactory(session.getDataSources()), new ArrayList<Action>(),
            componentList, owner, false, newDSTypes);
    dbConnectionManager.setDbIcon(DB_ICON);

    startImageLabel.addMouseListener(new MouseListener() {
        boolean inside = false;
        boolean pressed = false;

        public void mouseReleased(MouseEvent e) {
            pressed = false;
            SPDataSource ds = dbConnectionManager.getSelectedConnection();
            if (startImageLabel.isFocusOwner()) {
                startImageLabel.setIcon(SELECT_START_ICON);
                if (ds == null) {
                    JOptionPane.showMessageDialog(context.getFrame(),
                            "Please select a data source before pressing 'Start'",
                            "Please select a data source", JOptionPane.WARNING_MESSAGE);
                } else {
                    addDataSource(session, ds);
                }
            } else if (inside) {
                startImageLabel.setIcon(OVER_START_ICON);
                if (ds == null) {
                    JOptionPane.showMessageDialog(context.getFrame(),
                            "Please select a data source before pressing 'Start'",
                            "Please select a data source", JOptionPane.WARNING_MESSAGE);
                } else {
                    addDataSource(session, ds);
                }
            } else {
                startImageLabel.setIcon(UP_START_ICON);
            }
        }

        private void addDataSource(final WabitSwingSession session, SPDataSource ds) {
            if (ds instanceof JDBCDataSource) {
                addJDBCDataSource((JDBCDataSource) ds, session);
            } else if (ds instanceof Olap4jDataSource) {
                addOlap4jDataSource((Olap4jDataSource) ds, session);
            } else {
                throw new IllegalArgumentException(
                        "Unknown data source of type " + ds.getClass() + " is being added to the workspace.");
            }
        }

        public void mousePressed(MouseEvent e) {
            startImageLabel.requestFocusInWindow();
            pressed = true;
            startImageLabel.setIcon(DOWN_START_ICON);
        }

        public void mouseExited(MouseEvent e) {
            inside = false;
            if (startImageLabel.isFocusOwner()) {
                startImageLabel.setIcon(SELECT_START_ICON);
            } else if (pressed) {
                startImageLabel.setIcon(DOWN_START_ICON);
            } else {
                startImageLabel.setIcon(UP_START_ICON);
            }
        }

        public void mouseEntered(MouseEvent e) {
            inside = true;
            if (startImageLabel.isFocusOwner()) {
                startImageLabel.setIcon(SELECT_START_ICON);
            } else if (pressed) {
                startImageLabel.setIcon(DOWN_START_ICON);
            } else {
                startImageLabel.setIcon(OVER_START_ICON);
            }
        }

        public void mouseClicked(MouseEvent e) {
            // do nothing
        }
    });
    startImageLabel.addFocusListener(new FocusListener() {

        public void focusLost(FocusEvent e) {
            startImageLabel.setIcon(UP_START_ICON);
        }

        public void focusGained(FocusEvent e) {
            //do nothing.
        }
    });
    return dbConnectionManager;
}

From source file:calendarexportplugin.exporter.AppleSettingsDialog.java

License:Open Source License

private void createGui(final CalendarExportSettings settings) {
    setTitle(mLocalizer.msg("title", "iCal Calendar Settings"));

    UiUtilities.registerForClosing(this);

    JPanel content = (JPanel) getContentPane();
    content.setBorder(Borders.DLU4_BORDER);

    CellConstraints cc = new CellConstraints();

    content.setLayout(new FormLayout("5dlu, 15dlu, fill:pref:grow, 3dlu, 100dlu",
            "pref, 3dlu,pref, 3dlu,pref, 3dlu,pref, 3dlu,pref, 3dlu,pref, 3dlu,pref, 3dlu,pref, fill:3dlu:grow ,pref, 3dlu,pref"));

    content.add(new JLabel(mLocalizer.msg("select", "Select Calendar")), cc.xyw(2, 3, 2));
    mCalendarChooser = new JTextField();
    content.add(mCalendarChooser, cc.xy(5, 3));

    ButtonBarBuilder2 builder = new ButtonBarBuilder2();
    builder.addGlue();/*from  w  w w .  j a v a2 s  . c  om*/

    mOkButton = new JButton(Localizer.getLocalization(Localizer.I18N_OK));

    mOkButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            okPressed(settings);
        }
    });

    getRootPane().setDefaultButton(mOkButton);

    JButton cancel = new JButton(Localizer.getLocalization(Localizer.I18N_CANCEL));

    cancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            close();
        }
    });

    builder.addButton(new JButton[] { mOkButton, cancel });
    content.add(builder.getPanel(), cc.xyw(1, 19, 5));
    loadValues(settings);

    setSize(Sizes.dialogUnitXAsPixel(200, this), Sizes.dialogUnitYAsPixel(100, this));
}

From source file:calendarexportplugin.ExtendedDialog.java

License:Open Source License

/**
 * Create the GUI//w  w  w.j  a  va  2s  . c o  m
 */
private void createGui() {
    try {
        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(
                new FormLayout("5dlu,default:grow,5dlu", "pref,5dlu,fill:default:grow,5dlu,pref"),
                (JPanel) this.getContentPane());
        pb.setDefaultDialogBorder();

        mConfigPanel = new PluginProgramConfigurationPanel(
                CalendarExportPlugin.getInstance().getSelectedPluginProgramFormattings(),
                CalendarExportPlugin.getInstance().getAvailableLocalPluginProgramFormatings(),
                CalendarExportPlugin.getDefaultFormatting(), true, false);

        pb.addSeparator(mLocalizer.msg("title", "Formatings selection"), cc.xyw(1, 1, 3));
        pb.add(mConfigPanel, cc.xy(2, 3));

        FormLayout layout = new FormLayout("0dlu:grow,pref,5dlu,pref", "pref");
        layout.setColumnGroups(new int[][] { { 2, 4 } });

        JPanel buttonPanel = new JPanel(layout);

        JButton ok = new JButton(Localizer.getLocalization(Localizer.I18N_OK));

        ok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                okPressed();
            }
        });

        JButton cancel = new JButton(Localizer.getLocalization(Localizer.I18N_CANCEL));
        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cancelPressed();
            }
        });

        buttonPanel.add(ok, cc.xy(2, 1));
        buttonPanel.add(cancel, cc.xy(4, 1));

        pb.add(buttonPanel, cc.xy(2, 5));

        getRootPane().setDefaultButton(ok);

        setSize(550, 400);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:captureplugin.drivers.defaultdriver.configpanels.ApplicationPanel.java

License:Open Source License

/**
 * creates a JPanel for getting the programpath
 */// w w w .  j  av a  2s.c o m
private void createPanel() {
    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(
            new FormLayout("5dlu,pref,3dlu,pref:grow,3dlu,pref,2dlu", "pref,5dlu,pref,3dlu,pref"), this);
    pb.setDefaultDialogBorder();

    pb.addSeparator(mLocalizer.msg("What", "What to start"), cc.xyw(1, 1, 7));

    JRadioButton application = new JRadioButton(mLocalizer.msg("Application", "Application"));

    pb.add(application, cc.xy(2, 3));

    mPathTextField.setText(mData.getProgramPath());
    mPathTextField.addFocusListener(new FocusAdapter() {
        public void focusLost(FocusEvent e) {
            mData.setProgramPath(mPathTextField.getText());
        }
    });

    pb.add(mPathTextField, cc.xy(4, 3));

    mFileButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pathButtonPressed(e);
        }
    });

    pb.add(mFileButton, cc.xy(6, 3));

    JRadioButton url = new JRadioButton(mLocalizer.msg("URL", "URL"));

    pb.add(url, cc.xy(2, 5));

    mUrl.setText(mData.getWebUrl());

    mUrl.addFocusListener(new FocusAdapter() {
        public void focusLost(FocusEvent e) {
            mData.setWebUrl(mUrl.getText());
        }
    });

    pb.add(mUrl, cc.xyw(4, 5, 3));

    ButtonGroup group = new ButtonGroup();

    group.add(application);
    group.add(url);

    url.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setUrlMode(true);
        }
    });

    application.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            setUrlMode(false);
        }
    });

    if (mData.getUseWebUrl()) {
        url.setSelected(true);
    } else {
        application.setSelected(true);
    }

    setUrlMode(mData.getUseWebUrl());
}