Example usage for com.jgoodies.forms.layout CellConstraints xy

List of usage examples for com.jgoodies.forms.layout CellConstraints xy

Introduction

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

Prototype

public CellConstraints xy(int col, int row) 

Source Link

Document

Sets column and row origins; sets width and height to 1; uses the default alignments.

Examples:

 cc.xy(1, 1); cc.xy(1, 3); 

Usage

From source file:ca.phon.script.params.ui.ParamPanelFactory.java

License:Open Source License

private JPanel createComponentPanel(JLabel label, JComponent comp) {
    String cols = "20px, fill:pref:grow";
    String rows = "pref, pref";
    FormLayout layout = new FormLayout(cols, rows);
    JPanel compPanel = new JPanel(layout);
    CellConstraints cc = new CellConstraints();
    compPanel.add(label, cc.xyw(1, 1, 2));
    compPanel.add(comp, cc.xy(2, 2));

    return compPanel;
}

From source file:ca.phon.syllabifier.editor.SyllabifierSettingsPanel.java

License:Open Source License

private void init() {
    final FormLayout layout = new FormLayout("right:pref, fill:pref:grow", "pref, 3dlu, pref");
    setLayout(layout);//from w w  w  . j av  a2s  . c o m

    final CellConstraints cc = new CellConstraints();

    add(new JLabel("Syllabifier name:"), cc.xy(1, 1));
    nameField = new JTextField();
    add(nameField, cc.xy(2, 1));

    add(new JLabel("Syllabifier language:"), cc.xy(1, 3));
    languageField = new JTextField();
    add(languageField, cc.xy(2, 3));
}

From source file:ca.phon.ui.layout.ButtonBarBuilder.java

License:Open Source License

public JComponent build() {
    final CellConstraints cc = new CellConstraints();
    final FormLayout layout = new FormLayout(createColumnSchema(), "pref");

    final JPanel retVal = new JPanel(layout);

    int colIdx = 1;

    for (int i = 0; i < leftAlignedComponents.size(); i++) {
        final WeakReference<JComponent> buttonRef = leftAlignedComponents.get(i);
        final JComponent button = buttonRef.get();

        retVal.add(button, cc.xy(colIdx, 1));
        ++colIdx;// ww  w.j  a  v a2  s .co  m
    }
    if (colIdx == 1)
        ++colIdx;
    if (leftFillComponent != null) {
        retVal.add(leftFillComponent.get(), cc.xy(colIdx, 1));
    }
    ++colIdx;

    int oldIdx = colIdx;
    for (int i = 0; i < centerAlignedComponents.size(); i++) {
        final WeakReference<JComponent> buttonRef = centerAlignedComponents.get(i);
        final JComponent button = buttonRef.get();

        retVal.add(button, cc.xy(colIdx, 1));
        ++colIdx;
    }
    if (colIdx == oldIdx)
        ++colIdx;
    if (rightFillComponent != null) {
        retVal.add(rightFillComponent.get(), cc.xy(colIdx, 1));
    }
    ++colIdx;

    for (int i = 0; i < rightAlignedComponents.size(); i++) {
        final WeakReference<JComponent> buttonRef = rightAlignedComponents.get(i);
        final JComponent button = buttonRef.get();

        retVal.add(button, cc.xy(colIdx, 1));
        ++colIdx;
    }

    return retVal;
}

From source file:ca.phon.ui.participant.ParticipantPanel.java

License:Open Source License

private void init() {
    // setup form
    roleBox = new JComboBox(ParticipantRole.values());

    assignIdBox = new JCheckBox("Assign ID from role");
    assignIdBox.setSelected(true);//  w  ww. j a va 2s. c o m

    idField = new JTextField();
    idField.setEnabled(false);

    sexBox = new JComboBox(Sex.values());
    sexBox.setSelectedItem((participant.getSex() != null ? participant.getSex() : Sex.UNSPECIFIED));
    sexBox.setRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            final JLabel retVal = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
                    cellHasFocus);
            final Sex sex = (Sex) value;

            retVal.setText(sex.getText());

            return retVal;
        }

    });

    final PhonUIAction anonymizeAct = new PhonUIAction(this, "onAnonymize");
    anonymizeAct.putValue(PhonUIAction.NAME, "Anonymize");
    anonymizeAct.putValue(PhonUIAction.SHORT_DESCRIPTION, "Remove all optional information");
    anonymizeBtn = new JButton(anonymizeAct);

    int defCols = 20;
    nameField = new JTextField();
    nameField.setColumns(defCols);
    groupField = new JTextField();
    groupField.setColumns(defCols);
    sesField = new JTextField();
    sesField.setColumns(defCols);
    educationField = new JTextField();
    educationField.setColumns(defCols);
    languageField = new LanguageField();
    languageField.setColumns(defCols);

    bdayField = new DatePicker();
    ageField = FormatterTextField.createTextField(Period.class);
    ageField.setPrompt("YY;MM.DD");
    ageField.setToolTipText("Enter age in format YY;MM.YY");
    ageField.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent arg0) {
            if (ageField.getText().length() > 0 && !ageField.validateText()) {
                ToastFactory.makeToast("Age format: " + AgeFormatter.AGE_FORMAT).start(ageField);
                Toolkit.getDefaultToolkit().beep();
                bdayField.requestFocus();
            }
        }

        @Override
        public void focusGained(FocusEvent arg0) {
        }

    });

    // setup info

    if (participant.getRole() != null)
        roleBox.setSelectedItem(participant.getRole());
    if (participant.getId() != null) {
        idField.setText(participant.getId());
    }
    idField.setText(participant.getId());
    if (participant.getName() != null)
        nameField.setText(participant.getName());
    if (participant.getGroup() != null)
        groupField.setText(participant.getGroup());
    if (participant.getSES() != null)
        sesField.setText(participant.getSES());
    if (participant.getLanguage() != null)
        languageField.setText(participant.getLanguage());
    if (participant.getEducation() != null)
        educationField.setText(participant.getEducation());

    if (participant.getBirthDate() != null) {
        bdayField.setDateTime(participant.getBirthDate());
    }

    if (participant.getAge(null) != null) {
        ageField.setValue(participant.getAge(null));
    }

    // setup listeners
    final Functor<Void, Participant> roleUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            final ParticipantRole role = (ParticipantRole) roleBox.getSelectedItem();
            participant.setRole(role);
            if (assignIdBox.isSelected()) {
                idField.setText(getRoleId());
            }

            return null;
        }

    };
    roleBox.addItemListener(new ItemUpdater(roleUpdater));

    final Functor<Void, Participant> idUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setId(idField.getText());
            return null;
        }

    };
    idField.getDocument().addDocumentListener(new TextFieldUpdater(idUpdater));

    final Functor<Void, Participant> nameUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setName(nameField.getText());
            return null;
        }

    };
    nameField.getDocument().addDocumentListener(new TextFieldUpdater(nameUpdater));

    final Functor<Void, Participant> langUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setLanguage(languageField.getText());
            return null;
        }

    };
    languageField.getDocument().addDocumentListener(new TextFieldUpdater(langUpdater));

    final Functor<Void, Participant> groupUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setGroup(groupField.getText());
            return null;
        }

    };
    groupField.getDocument().addDocumentListener(new TextFieldUpdater(groupUpdater));

    final Functor<Void, Participant> eduUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setEducation(educationField.getText());
            return null;
        }

    };
    educationField.getDocument().addDocumentListener(new TextFieldUpdater(eduUpdater));

    final Functor<Void, Participant> sesUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setSES(sesField.getText());
            return null;
        }

    };
    sesField.getDocument().addDocumentListener(new TextFieldUpdater(sesUpdater));

    final Functor<Void, Participant> sexUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            participant.setSex((Sex) sexBox.getSelectedItem());
            return null;
        }

    };
    sexBox.addItemListener(new ItemUpdater(sexUpdater));

    final Functor<Void, Participant> assignIdFunctor = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            if (assignIdBox.isSelected()) {
                if (assignIdBox.isSelected()) {
                    idField.setText(getRoleId());
                }
            }
            idField.setEnabled(!assignIdBox.isSelected());
            return null;
        }

    };
    assignIdBox.addItemListener(new ItemUpdater(assignIdFunctor));

    final Functor<Void, Participant> bdayUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            final LocalDate bday = bdayField.getDateTime();
            participant.setBirthDate(bday);
            if (participant.getAge(null) == null) {
                if (sessionDate != null && sessionDate.isAfter(participant.getBirthDate())) {
                    final Period age = participant.getAge(sessionDate);
                    ageField.setPrompt(AgeFormatter.ageToString(age));
                    ageField.setKeepPrompt(true);
                } else {
                    ageField.setPrompt("YY:MM.DD");
                    ageField.setKeepPrompt(false);
                }
            }
            return null;
        }

    };
    bdayField.getTextField().getDocument().addDocumentListener(new TextFieldUpdater(bdayUpdater));
    bdayField.getTextField().addActionListener(new ActionUpdater(bdayUpdater));

    final Functor<Void, Participant> ageUpdater = new Functor<Void, Participant>() {

        @Override
        public Void op(Participant obj) {
            if (ageField.getText().trim().length() == 0) {
                participant.setAge(null);
            } else {
                final Period p = ageField.getValue();
                participant.setAge(p);
            }
            return null;
        }

    };
    ageField.getDocument().addDocumentListener(new TextFieldUpdater(ageUpdater));

    // ensure a role is selected!
    if (participant.getRole() == null) {
        roleBox.setSelectedItem(ParticipantRole.TARGET_CHILD);
    }

    final CellConstraints cc = new CellConstraints();
    final FormLayout reqLayout = new FormLayout("right:pref, 3dlu, fill:pref:grow", "pref, pref, pref");
    final JPanel required = new JPanel(reqLayout);
    required.setBorder(BorderFactory.createTitledBorder("Required Information"));
    required.add(new JLabel("Role"), cc.xy(1, 1));
    required.add(roleBox, cc.xy(3, 1));
    required.add(assignIdBox, cc.xy(3, 2));
    required.add(new JLabel("Id"), cc.xy(1, 3));
    required.add(idField, cc.xy(3, 3));

    final FormLayout optLayout = new FormLayout(
            "right:pref, 3dlu, fill:pref:grow, 5dlu, right:pref, 3dlu, fill:pref:grow",
            "pref, pref, pref, pref");
    final JPanel optional = new JPanel(optLayout);
    optional.setBorder(BorderFactory.createTitledBorder("Optional Information"));
    optional.add(new JLabel("Name"), cc.xy(1, 1));
    optional.add(nameField, cc.xy(3, 1));
    optional.add(new JLabel("Sex"), cc.xy(1, 2));
    optional.add(sexBox, cc.xy(3, 2));
    optional.add(new JLabel("Birthday (" + DateFormatter.DATETIME_FORMAT + ")"), cc.xy(1, 3));
    optional.add(bdayField, cc.xy(3, 3));
    optional.add(new JLabel("Age (" + AgeFormatter.AGE_FORMAT + ")"), cc.xy(1, 4));
    optional.add(ageField, cc.xy(3, 4));

    optional.add(new JLabel("Language"), cc.xy(5, 1));
    optional.add(languageField, cc.xy(7, 1));
    optional.add(new JLabel("Group"), cc.xy(5, 2));
    optional.add(groupField, cc.xy(7, 2));
    optional.add(new JLabel("Education"), cc.xy(5, 3));
    optional.add(educationField, cc.xy(7, 3));
    optional.add(new JLabel("SES"), cc.xy(5, 4));
    optional.add(sesField, cc.xy(7, 4));

    setLayout(new VerticalLayout(5));
    add(required);
    add(optional);
    add(ButtonBarBuilder.buildOkBar(anonymizeBtn));
    add(new JSeparator(SwingConstants.HORIZONTAL));
}

From source file:ca.phon.ui.text.FileSelectionField.java

License:Open Source License

private void init() {
    final FormLayout layout = new FormLayout("fill:pref:grow, pref", "pref");
    final CellConstraints cc = new CellConstraints();
    setLayout(layout);//from   w  w w .ja  v  a 2 s.  c om

    textField = new PromptedTextField();
    add(textField, cc.xy(1, 1));

    final ImageIcon browseIcon = IconManager.getInstance().getIcon("actions/document-open", IconSize.SMALL);
    final PhonUIAction browseAct = new PhonUIAction(this, "onBrowse");
    browseAct.putValue(PhonUIAction.SHORT_DESCRIPTION, "Browse...");
    browseAct.putValue(PhonUIAction.SMALL_ICON, browseIcon);
    browseButton = new JButton(browseAct);
    browseButton.putClientProperty("JButton.buttonType", "square");
    browseButton.setCursor(Cursor.getDefaultCursor());
    add(browseButton, cc.xy(2, 1));

    setBorder(textField.getBorder());
    textField.setBorder(null);

    textField.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            final File f = getSelectedFile();
            setFile(f);
        }
    });
}

From source file:ca.phon.ui.text.SearchField.java

License:Open Source License

private void init() {
    final FormLayout layout = new FormLayout("pref, 3dlu, fill:pref:grow, 3dlu, pref", "pref");
    setLayout(layout);//from  w w  w.j av  a  2s .com
    final CellConstraints cc = new CellConstraints();

    // load search icon
    final ImageIcon searchIcon = new ImageIcon(createSearchIcon());
    final PhonUIAction ctxAction = new PhonUIAction(this, "onShowContextMenu");
    ctxAction.putValue(PhonUIAction.SMALL_ICON, searchIcon);
    ctxAction.putValue(PhonUIAction.SHORT_DESCRIPTION, "Click for options");
    ctxButton = new SearchFieldButton(ctxAction);
    ctxButton.setCursor(Cursor.getDefaultCursor());
    ctxButton.setFocusable(false);
    add(ctxButton, cc.xy(1, 1));

    add(queryField, cc.xy(3, 1));

    final ImageIcon clearIcon = new ImageIcon(createClearIcon());
    final PhonUIAction clearTextAct = new PhonUIAction(this, "onClearText");
    clearTextAct.putValue(PhonUIAction.SMALL_ICON, clearIcon);
    clearTextAct.putValue(PhonUIAction.SHORT_DESCRIPTION, "Clear field");
    endButton = new SearchFieldButton(clearTextAct);
    endButton.setCursor(Cursor.getDefaultCursor());
    endButton.setDrawIcon(false);
    add(endButton, cc.xy(5, 1));

    setBorder(queryField.getBorder());
    final Insets insets = queryField.getBorder().getBorderInsets(queryField);
    queryField.setBorder(BorderFactory.createEmptyBorder(insets.top, insets.left, insets.bottom, insets.right));
}

From source file:ca.phon.ui.wizard.WizardFrame.java

License:Open Source License

private void init() {
    // step panel
    stepLayout = new CardLayout();
    stepPanel = new JPanel(stepLayout);
    add(stepPanel, BorderLayout.CENTER);

    // button bar
    ImageIcon icnBack = IconManager.getInstance().getIcon("actions/agt_back", IconSize.SMALL);
    ImageIcon icnNext = IconManager.getInstance().getIcon("actions/agt_forward", IconSize.SMALL);
    ImageIcon icnFinish = IconManager.getInstance().getIcon("actions/button_ok", IconSize.SMALL);
    ImageIcon icnCancel = IconManager.getInstance().getIcon("actions/button_cancel", IconSize.SMALL);

    btnBack = new JButton("Back");
    btnBack.setIcon(icnBack);/* w  w w.j  a v a2s .c om*/
    btnBack.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            prev();
        }

    });

    btnNext = new JButton("Next");
    btnNext.setIcon(icnNext);
    btnNext.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            next();
        }
    });

    btnNext.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    btnFinish = new JButton("Finish");
    btnFinish.setIcon(icnFinish);
    btnFinish.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            finish();
        }

    });
    super.getRootPane().setDefaultButton(btnFinish);

    btnCancel = new JButton("Close");
    btnCancel.setIcon(icnCancel);
    btnCancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel();
        }

    });

    FormLayout barLayout = new FormLayout("fill:pref:grow, pref, pref, 5dlu, pref, pref", "pref");
    CellConstraints cc = new CellConstraints();
    JPanel buttonPanel = new JPanel(barLayout);

    buttonPanel.add(btnBack, cc.xy(2, 1));
    buttonPanel.add(btnNext, cc.xy(3, 1));
    buttonPanel.add(btnFinish, cc.xy(5, 1));
    buttonPanel.add(btnCancel, cc.xy(6, 1));
    buttonPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.DARK_GRAY));

    add(buttonPanel, BorderLayout.SOUTH);
}

From source file:ca.sqlpower.architect.swingui.action.ProgressAction.java

License:Open Source License

/**
 * Setup the dialog, monitors and worker.  Classes that extend this class
 * should use doStuff() and cleanUp()//from   w  w  w .  j  a  v  a 2 s  .c  o  m
 */
public void actionPerformed(ActionEvent e) {
    final JDialog progressDialog;
    final Map<String, Object> properties = new HashMap<String, Object>();
    progressDialog = new JDialog(frame, Messages.getString("ProgressAction.name"), false); //$NON-NLS-1$
    progressDialog.setLocationRelativeTo(frame);
    progressDialog.setTitle(getDialogMessage());

    PanelBuilder pb = new PanelBuilder(
            new FormLayout("4dlu,fill:min(100dlu;default):grow, pref, fill:min(100dlu;default):grow,4dlu", //$NON-NLS-1$
                    "4dlu,pref,4dlu, pref, 6dlu, pref,4dlu")); //$NON-NLS-1$
    JLabel label = new JLabel(getDialogMessage());
    JProgressBar progressBar = new JProgressBar();
    final MonitorableImpl monitor = new MonitorableImpl();
    if (!setup(monitor, properties)) {
        // if setup indicates not to continue (returns false), then exit method
        return;
    }
    CellConstraints c = new CellConstraints();
    pb.add(label, c.xyw(2, 2, 3));
    pb.add(progressBar, c.xyw(2, 4, 3));
    pb.add(new JButton(new AbstractAction(getButtonText()) {
        public void actionPerformed(ActionEvent e) {
            progressDialog.dispose();
            monitor.setCancelled(true);
        }
    }), c.xy(3, 6));
    progressDialog.add(pb.getPanel());

    SPSwingWorker worker = new SPSwingWorker(getSession()) {
        @Override
        public void cleanup() throws Exception {
            if (getDoStuffException() != null) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ProgressAction.unexpectedException"), getDoStuffException()); //$NON-NLS-1$
            }
            ProgressAction.this.cleanUp(monitor);
            monitor.setFinished(true);
            progressDialog.dispose();
        }

        @Override
        public void doStuff() throws Exception {
            ProgressAction.this.doStuff(monitor, properties);
        }
    };
    ProgressWatcher.watchProgress(progressBar, monitor);
    progressDialog.pack();
    progressDialog.setVisible(true);

    new Thread(worker).start();
}

From source file:ca.sqlpower.architect.swingui.ColumnEditPanel.java

License:Open Source License

public ColumnEditPanel(Collection<SQLColumn> cols, final ArchitectSwingSession session)
        throws SQLObjectException {
    logger.debug("ColumnEditPanel called"); //$NON-NLS-1$

    if (session == null) {
        throw new NullPointerException("Null session is not allowed"); //$NON-NLS-1$
    }//w ww .  java2  s  .c o m
    this.session = session;

    if (cols == null || cols.isEmpty()) {
        throw new NullPointerException("Null or empty collection of columns is not allowed"); //$NON-NLS-1$
    }
    columns = new ArrayList<SQLColumn>(cols);

    //        if (columns.get(0).getParent() != null) {
    //            columns.get(0).getParent().getPrimaryKeyIndex().addSPListener(this);
    //            for (SQLColumn col : columns) {
    //                col.addSPListener(this);
    //            }
    //        }

    FormLayout layout = new FormLayout("pref, pref, pref:grow, 4dlu, pref, pref:grow", "");
    layout.setColumnGroups(new int[][] { { 3, 6 } });
    panel = new JPanel(layout);
    CellConstraints cc = new CellConstraints();

    JCheckBox cb;
    int row = 1;
    int width = 5;
    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.source")), cc.xyw(2, row++, width)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("p"));

    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row));
    }

    colSourceTree = new JTree();
    DBTreeModel sourceTreeModel = new DBTreeModel(session.getRootObject(), colSourceTree, false, true, false,
            false, false) {
        @Override
        public Object getChild(Object parent, int index) {
            if (parent == sourceNotSpecifiedTreeNode) {
                return null;
            } else if (parent == getRoot()) {
                if (index == 0) {
                    return sourceNotSpecifiedTreeNode;
                } else {
                    return super.getChild(parent, index - 1);
                }
            } else {
                return super.getChild(parent, index);
            }
        }

        @Override
        public int getChildCount(Object parent) {
            if (parent == sourceNotSpecifiedTreeNode) {
                return 0;
            } else if (parent == getRoot()) {
                return super.getChildCount(parent) + 1;
            } else {
                return super.getChildCount(parent);
            }
        }

        @Override
        public int getIndexOfChild(Object parent, Object child) {
            if (parent == sourceNotSpecifiedTreeNode) {
                return -1;
            } else if (child == sourceNotSpecifiedTreeNode) {
                return 0;
            } else if (parent == getRoot()) {
                int index = super.getIndexOfChild(parent, child);
                if (index != -1) {
                    return index + 1;
                } else {
                    return -1;
                }
            } else {
                return super.getIndexOfChild(parent, child);
            }
        }

        @Override
        public boolean isLeaf(Object parent) {
            if (parent == sourceNotSpecifiedTreeNode) {
                return true;
            } else {
                return super.isLeaf(parent);
            }
        }

    };
    colSourceTree.setModel(sourceTreeModel);
    colSourceTree.setRootVisible(false);
    colSourceTree.setShowsRootHandles(true);
    colSourceTree.setCellRenderer(new DBTreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            if (!sel && value == sourceNotSpecifiedTreeNode) {
                setForeground(getTextNonSelectionColor());
            }
            return this;
        }
    });
    colSourceTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    colSourceButton = new JButton();
    colSourceButton.setAction(new PopupJTreeAction(panel, colSourceTree, colSourceButton, SQLColumn.class));

    panel.add(colSourceButton, cc.xyw(2, row++, 2));
    componentEnabledMap.put(colSourceTree, cb);

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.logicalName")), cc.xyw(2, row++, width)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("p"));
    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row));
    }
    panel.add(colLogicalName = new JTextField(), cc.xyw(2, row++, width));
    componentEnabledMap.put(colLogicalName, cb);
    colLogicalName.getDocument().addDocumentListener(new DocumentCheckboxEnabler(cb));
    colLogicalName.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent e) {
            colLogicalName.requestFocusInWindow();
        }
    });
    colLogicalName.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            if (logger.isDebugEnabled()) {
                logger.debug("focus Gained : " + e);
            }
            colLogicalName.selectAll();
        }
    });

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.physicalName")), cc.xyw(2, row++, width)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("p"));
    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row));
    }
    panel.add(colPhysicalName = new JTextField(), cc.xyw(2, row++, width));
    componentEnabledMap.put(colPhysicalName, cb);
    colPhysicalName.getDocument().addDocumentListener(new DocumentCheckboxEnabler(cb));
    colPhysicalName.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent e) {
            colPhysicalName.requestFocusInWindow();
        }
    });
    colPhysicalName.addFocusListener(new FocusAdapter() {
        public void focusGained(FocusEvent e) {
            if (logger.isDebugEnabled()) {
                logger.debug("focus Gained : " + e);
            }
            colPhysicalName.selectAll();
        }
    });

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row));
    }
    panel.add(colInPK = new JCheckBox(Messages.getString("ColumnEditPanel.inPrimaryKey")), //$NON-NLS-1$
            cc.xyw(2, row++, width));
    componentEnabledMap.put(colInPK, cb);
    colInPK.addActionListener(this);
    colInPK.addActionListener(checkboxEnabler);

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.type")), cc.xyw(2, row++, width)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("p"));
    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row));
    }

    typeChooserButton = new JButton(Messages.getString("ColumnEditPanel.chooseType"));

    if (session.isEnterpriseSession()) {
        colType = new JTree(new SQLTypeTreeModel(session.getEnterpriseSession()));
    } else {
        colType = new JTree(new SQLTypeTreeModel(session));
    }

    colType.setCellRenderer(new SQLTypeTreeCellRenderer());
    for (int i = 0; i < colType.getRowCount(); i++) {
        colType.expandRow(i);
    }
    colType.setRootVisible(true);
    colType.setShowsRootHandles(true);
    colType.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    typeChooserButton
            .setAction(new PopupJTreeAction(panel, colType, typeChooserButton, UserDefinedSQLType.class));

    componentEnabledMap.put(colType, cb);
    panel.add(typeChooserButton, cc.xyw(2, row++, 2));

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.precision")), cc.xy(3, row)); //$NON-NLS-1$
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.scale")), cc.xy(6, row++)); //$NON-NLS-1$

    layout.appendRow(RowSpec.decode("p"));
    panel.add(colPrec = createPrecisionEditor(), cc.xy(3, row));
    colPrec.addChangeListener(checkboxEnabler);
    SPSUtils.makeJSpinnerSelectAllTextOnFocus(colPrec);
    colPrecCB = new JCheckBox();
    panel.add(colPrecCB, cc.xy(2, row));
    typeOverrideMap.put(colPrec, colPrecCB);
    colPrecCB.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (colPrecCB.isSelected()) {
                colPrec.setEnabled(true);
            } else {
                colPrec.setEnabled(false);
                if (colType.getLastSelectedPathComponent() instanceof UserDefinedSQLType) {
                    colPrec.setValue(((UserDefinedSQLType) colType.getLastSelectedPathComponent())
                            .getPrecision(SQLTypePhysicalPropertiesProvider.GENERIC_PLATFORM));
                }
            }
        }
    });
    colPrec.setEnabled(false);

    colScaleCB = new JCheckBox();
    panel.add(colScaleCB, cc.xy(5, row));
    panel.add(colScale = createScaleEditor(), cc.xy(6, row++));
    typeOverrideMap.put(colScale, colScaleCB);
    colScale.addChangeListener(checkboxEnabler);
    SPSUtils.makeJSpinnerSelectAllTextOnFocus(colScale);
    colScaleCB.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (colScaleCB.isSelected()) {
                colScale.setEnabled(true);
            } else {
                colScale.setEnabled(false);
                if (colType.getLastSelectedPathComponent() instanceof UserDefinedSQLType) {
                    colScale.setValue(((UserDefinedSQLType) colType.getLastSelectedPathComponent())
                            .getScale(SQLTypePhysicalPropertiesProvider.GENERIC_PLATFORM));
                }
            }
        }
    });
    colScale.setEnabled(false);

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.allowsNulls")), cc.xyw(3, row++, width - 1)); //$NON-NLS-1$

    layout.appendRow(RowSpec.decode("p"));
    final JCheckBox colNullCB = new JCheckBox();
    panel.add(colNullCB, cc.xy(2, row));
    panel.add(colNullable = new JComboBox(YesNoEnum.values()), cc.xy(3, row++)); //$NON-NLS-1$
    typeOverrideMap.put(colNullable, colNullCB);
    colNullable.addActionListener(this);
    colNullable.addActionListener(checkboxEnabler);
    colNullCB.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (colNullCB.isSelected()) {
                colNullable.setEnabled(true);
            } else {
                colNullable.setEnabled(false);
                if (colType.getLastSelectedPathComponent() instanceof UserDefinedSQLType) {
                    colNullable.setSelectedItem(
                            YesNoEnum.valueOf(((UserDefinedSQLType) colType.getLastSelectedPathComponent())
                                    .getNullability() == DatabaseMetaData.columnNullable));
                }
            }
            updateComponents();
        }
    });
    colNullable.setEnabled(false);

    layout.appendRow(RowSpec.decode("3dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.autoIncrement")), cc.xyw(3, row++, width - 1)); //$NON-NLS-1$

    layout.appendRow(RowSpec.decode("p"));
    final JCheckBox colAutoIncCB = new JCheckBox();
    panel.add(colAutoIncCB, cc.xy(2, row));
    panel.add(colAutoInc = new JComboBox(YesNoEnum.values()), cc.xy(3, row++)); //$NON-NLS-1$
    typeOverrideMap.put(colAutoInc, colAutoIncCB);
    colAutoInc.addActionListener(this);
    colAutoInc.addActionListener(checkboxEnabler);
    colAutoIncCB.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (colAutoIncCB.isSelected()) {
                colAutoInc.setEnabled(true);
            } else {
                colAutoInc.setEnabled(false);
                if (colType.getLastSelectedPathComponent() instanceof UserDefinedSQLType) {
                    colAutoInc.setSelectedItem(YesNoEnum.valueOf(
                            ((UserDefinedSQLType) colType.getLastSelectedPathComponent()).getAutoIncrement()));
                }
            }
        }
    });
    colAutoInc.setEnabled(false);

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.defaultValue")), cc.xyw(3, row++, width - 1)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("p"));
    final JCheckBox colDefaultCB = new JCheckBox();
    panel.add(colDefaultCB, cc.xy(2, row));
    panel.add(colDefaultValue = new JTextField(), cc.xyw(3, row++, width - 1));
    colDefaultValue.setEnabled(false);

    typeOverrideMap.put(colDefaultValue, colDefaultCB);
    colDefaultValue.addActionListener(this);
    colDefaultCB.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            if (colDefaultCB.isSelected()) {
                colDefaultValue.setEnabled(true);
            } else {
                colDefaultValue.setEnabled(false);
                if (colType.getLastSelectedPathComponent() instanceof UserDefinedSQLType) {
                    colDefaultValue.setText(((UserDefinedSQLType) colType.getLastSelectedPathComponent())
                            .getDefaultValue(SQLTypePhysicalPropertiesProvider.GENERIC_PLATFORM));
                }
            }
            updateComponents();
        }
    });

    layout.appendRow(RowSpec.decode("6dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.sequenceName")), cc.xyw(2, row++, width)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("p"));
    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row));
    }
    panel.add(colAutoIncSequenceName = new JTextField(), cc.xyw(2, row++, width));
    componentEnabledMap.put(colAutoIncSequenceName, cb);
    colAutoIncSequenceName.getDocument().addDocumentListener(new DocumentCheckboxEnabler(cb));

    DocumentListener listener = new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            syncSequenceName();
        }

        public void insertUpdate(DocumentEvent e) {
            syncSequenceName();
        }

        public void removeUpdate(DocumentEvent e) {
            syncSequenceName();
        }
    };
    // Listener to update the sequence name when the column name changes
    colPhysicalName.getDocument().addDocumentListener(listener);
    colLogicalName.getDocument().addDocumentListener(listener);

    // Listener to rediscover the sequence naming convention, and reset the
    // sequence name to its original (according to the column's own sequence
    // name) naming convention when the user clears the sequence name field
    colAutoIncSequenceName.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            if (columns.size() == 1 && colAutoIncSequenceName.getText().trim().equals("")) { //$NON-NLS-1$
                // Changing sequence name doesn't make sense in multi-edit
                // because sequence names have to be unique
                SQLColumn column = columns.iterator().next();
                if (column.getPhysicalName() != null && !column.getPhysicalName().trim().equals("")) {
                    discoverSequenceNamePattern(column.getPhysicalName());
                } else {
                    discoverSequenceNamePattern(column.getName());
                }
                syncSequenceName();
            } else {
                if (colPhysicalName.getText() != null && !colPhysicalName.getText().trim().equals("")) {
                    discoverSequenceNamePattern(colPhysicalName.getText());
                } else {
                    discoverSequenceNamePattern(colLogicalName.getText());
                }
            }
        }
    });

    layout.appendRow(RowSpec.decode("5dlu"));
    row++;

    layout.appendRow(RowSpec.decode("p"));
    panel.add(makeTitle(Messages.getString("ColumnEditPanel.remarks")), cc.xyw(2, row++, width)); //$NON-NLS-1$
    layout.appendRow(RowSpec.decode("pref:grow"));
    cb = new JCheckBox();
    if (cols.size() > 1) {
        panel.add(cb, cc.xy(1, row, "center, top"));
    }
    panel.add(new JScrollPane(colRemarks = new JTextArea()), cc.xyw(2, row++, width, "fill, fill"));
    componentEnabledMap.put(colRemarks, cb);
    colRemarks.getDocument().addDocumentListener(new DocumentCheckboxEnabler(cb));
    colRemarks.setRows(5);
    colRemarks.setLineWrap(true);
    colRemarks.setWrapStyleWord(true);

    // start with all components enabled; if there are multiple columns
    // to edit, these checkboxes will be turned off selectively for the
    // mismatching values
    for (JCheckBox checkbox : componentEnabledMap.values()) {
        checkbox.setSelected(true);
    }

    //The type covers multiple fields and needs a different check to see if
    //it should start enabled. All type info must match across the objects
    //for the checkbox to start selected
    if (cols.size() > 1) {
        Iterator<SQLColumn> colIterator = cols.iterator();
        SQLColumn firstCol = colIterator.next();
        while (colIterator.hasNext()) {
            SQLColumn nextCol = colIterator.next();
            if (!firstCol.getTypeName().equals(nextCol.getTypeName())
                    || firstCol.getPrecision() != nextCol.getPrecision()
                    || firstCol.getScale() != nextCol.getScale()
                    || firstCol.getNullable() != nextCol.getNullable()
                    || firstCol.isAutoIncrement() != nextCol.isAutoIncrement()
                    || !firstCol.getDefaultValue().equals(nextCol.getDefaultValue())) {
                componentEnabledMap.get(colType).setSelected(false);
                break;
            }
        }
    }

    for (SQLColumn col : cols) {
        logger.debug("Updating component state for column " + col);
        updateComponents(col);
    }

    //         TODO only give focus to column name if it's enabled?
    colPhysicalName.requestFocus();
    colPhysicalName.selectAll();

    SQLPowerUtils.listenToHierarchy(session.getRootObject(), obsolesenceListener);
    SQLPowerUtils.listenToHierarchy(session.getRootObject(), this);
    panel.addAncestorListener(cleanupListener);

    colSourceTree.addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getNewLeadSelectionPath();
            if (path != null) {
                Object selection = path.getLastPathComponent();
                if (selection instanceof SQLColumn) {
                    SQLColumn sourceColumn = (SQLColumn) selection;
                    colSourceButton.setText(
                            DDLUtils.toQualifiedName(sourceColumn.getParent()) + "." + sourceColumn.getName());
                } else {
                    colSourceButton.setText(Messages.getString("ColumnEditPanel.noneSpecified"));
                }
            } else {
                colSourceButton.setText(Messages.getString("ColumnEditPanel.noneSpecified"));
            }
        }
    });

    colType.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getNewLeadSelectionPath();
            if (path != null) {
                Object selection = path.getLastPathComponent();
                if (selection instanceof UserDefinedSQLType) {
                    typeChooserButton.setText(((UserDefinedSQLType) selection).getName());
                    updateSQLTypeComponents((UserDefinedSQLType) selection, false);
                } else {
                    typeChooserButton.setText(Messages.getString("ColumnEditPanel.chooseType"));
                }
            } else {
                typeChooserButton.setText(Messages.getString("ColumnEditPanel.chooseType"));
            }
        }
    });
}

From source file:ca.sqlpower.architect.swingui.CompareDMFrame.java

License:Open Source License

public JComponent mainFrame() {

    FormLayout layout = new FormLayout(
            "4dlu,fill:min(150dlu;default):grow, 6dlu, fill:min(150dlu;default):grow, 4dlu", // columns //$NON-NLS-1$
            " min(300dlu;default), 6dlu, min(300dlu;default), 6dlu,  min(300dlu;default), 3dlu, fill:min(300dlu;default):grow, 3dlu, 20dlu,6dlu,20dlu"); // rows //$NON-NLS-1$

    CellConstraints cc = new CellConstraints();
    JLabel titleLabel = new JLabel(title);
    Font oldFont = titleLabel.getFont();
    Font titleFont = new Font(oldFont.getName(), oldFont.getStyle(), oldFont.getSize() * 2);

    titleLabel.setFont(titleFont);/*w  ww . jav  a 2 s .  c o m*/
    JLabel subTitleLabel = new JLabel(whatTheHeckIsGoingOn);
    leftOutputArea = new JTextPane();
    leftOutputArea.setMargin(new Insets(6, 10, 4, 6));
    leftOutputArea.setDocument(sourceOutputText);
    leftOutputArea.setEditable(false);
    JPanel comparePanel = new JPanel(new GridLayout(1, 2));
    JScrollPane sp = new JScrollPane(comparePanel);

    int lineHeight = 16;
    try {
        FontMetrics fm = leftOutputArea.getFontMetrics(leftOutputArea.getFont());
        lineHeight = fm.getHeight() + 2;
    } catch (Exception e) {
        lineHeight = 16;
    }
    // If the increments are not set, klicking on the up or down arrow of the scrollbar
    // will scroll the display by one pixel, which is definitely not what the user wants
    // by setting unitIncrement to the font's height the display will scroll by approx. one line
    sp.getVerticalScrollBar().setUnitIncrement(lineHeight);

    // Clicking in the "empty" area of the scrollbar will scroll by 10 lines
    sp.getVerticalScrollBar().setBlockIncrement(lineHeight * 10);

    comparePanel.add(leftOutputArea);
    Action sourceCopy = new sourceCopyAction(sourceOutputText);

    Action sourceSave = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            SPSUtils.saveDocument(CompareDMFrame.this, sourceOutputText,
                    (FileExtensionFilter) SPSUtils.TEXT_FILE_FILTER);
        }
    };
    CloseAction close = new CloseAction();
    close.setDialog(this);
    SPSUtils.makeJDialogCancellable(this, close);

    ButtonBarBuilder sourcebbBuilder = new ButtonBarBuilder();
    JButton copySource = new JButton(sourceCopy);
    copySource.setText(Messages.getString("CompareDMFrame.copy")); //$NON-NLS-1$
    sourcebbBuilder.addGridded(copySource);
    sourcebbBuilder.addRelatedGap();
    sourcebbBuilder.addGlue();

    JButton sourceSaveButton = new JButton(sourceSave);
    sourceSaveButton.setText(Messages.getString("CompareDMFrame.save")); //$NON-NLS-1$
    sourcebbBuilder.addGridded(sourceSaveButton);
    sourcebbBuilder.addRelatedGap();
    sourcebbBuilder.addGlue();

    ButtonBarBuilder closeBar = new ButtonBarBuilder();
    JButton closeButton = new JButton(close);
    closeButton.setText(Messages.getString("CompareDMFrame.close")); //$NON-NLS-1$
    closeBar.addGridded(closeButton);
    PanelBuilder pb;

    layout.setColumnGroups(new int[][] { { 2, 4 } });
    JPanel p = logger.isDebugEnabled() ? new FormDebugPanel(layout) : new JPanel(layout);

    pb = new PanelBuilder(layout, p);
    pb.setDefaultDialogBorder();

    rightOutputArea = new JTextPane();
    rightOutputArea.setMargin(new Insets(6, 10, 4, 6));
    rightOutputArea.setDocument(targetOutputText);
    rightOutputArea.setEditable(false);
    comparePanel.add(rightOutputArea);
    Action targetCopy = new targetCopyAction(targetOutputText);
    //Sets the target Buttons
    ButtonBarBuilder targetbbBuilder = new ButtonBarBuilder();
    JButton copyTarget = new JButton(targetCopy);
    copyTarget.setText(Messages.getString("CompareDMFrame.copy")); //$NON-NLS-1$
    targetbbBuilder.addGridded(copyTarget);
    targetbbBuilder.addRelatedGap();
    targetbbBuilder.addGlue();

    Action targetSaveAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            SPSUtils.saveDocument(CompareDMFrame.this, targetOutputText,
                    (FileExtensionFilter) SPSUtils.TEXT_FILE_FILTER);
        }
    };

    JButton targetSave = new JButton(targetSaveAction);
    targetSave.setText(Messages.getString("CompareDMFrame.save")); //$NON-NLS-1$
    targetbbBuilder.addGridded(targetSave);
    targetbbBuilder.addRelatedGap();
    targetbbBuilder.addGlue();
    getRootPane().setDefaultButton(targetSave);

    pb.add(titleLabel, cc.xyw(2, 1, 3, "c,c")); //$NON-NLS-1$
    pb.add(subTitleLabel, cc.xyw(2, 3, 3, "c,c")); //$NON-NLS-1$
    pb.add(new JLabel(Messages.getString("CompareDMFrame.older")), cc.xy(2, 5)); //$NON-NLS-1$
    pb.add(new JLabel(Messages.getString("CompareDMFrame.newer")), cc.xy(4, 5)); //$NON-NLS-1$
    pb.add(sp, cc.xyw(2, 7, 3));
    pb.add(sourcebbBuilder.getPanel(), cc.xy(2, 9, "l,c")); //$NON-NLS-1$
    pb.add(targetbbBuilder.getPanel(), cc.xy(4, 9, "r,c")); //$NON-NLS-1$
    pb.add(closeBar.getPanel(), cc.xy(4, 11, "r,c")); //$NON-NLS-1$

    return pb.getPanel();
}