Example usage for com.jgoodies.forms.builder DefaultFormBuilder DefaultFormBuilder

List of usage examples for com.jgoodies.forms.builder DefaultFormBuilder DefaultFormBuilder

Introduction

In this page you can find the example usage for com.jgoodies.forms.builder DefaultFormBuilder DefaultFormBuilder.

Prototype

public DefaultFormBuilder(FormLayout layout, StringResourceAccessor localizer) 

Source Link

Document

Constructs a DefaultFormBuilder for the given layout and resource bundle.

Usage

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

License:Open Source License

public RelationshipEditPanel(Relationship r) {

    relationshipLine = r;//from   ww w .j  a  va  2s  . c  o m
    this.color = relationshipLine.getForegroundColor();

    FormLayout layout = new FormLayout("pref, 4dlu, pref:grow, 4dlu, pref, 4dlu, pref:grow, 4dlu, pref"); //$NON-NLS-1$
    layout.setColumnGroups(new int[][] { { 3, 7 } });
    DefaultFormBuilder fb = new DefaultFormBuilder(layout,
            logger.isDebugEnabled() ? new FormDebugPanel() : new JPanel());

    fb.append(Messages.getString("RelationshipEditPanel.name"), relationshipName = new JTextField(), 7); //$NON-NLS-1$

    fb.nextLine();
    fb.append(Messages.getString("RelationshipEditPanel.lineColour"), //$NON-NLS-1$
            relationLineColor = new JComboBox(Relationship.SUGGESTED_COLOURS));
    ColorCellRenderer renderer = new ColorCellRenderer(40, 20);
    relationLineColor.setRenderer(renderer);
    if (!containsColor(Relationship.SUGGESTED_COLOURS, color)) {
        relationLineColor.addItem(color);
        relationLineColor.setSelectedItem(color);
    }
    fb.append(new JButton(customColour));

    fb.nextLine();
    fb.append(Messages.getString("RelationshipEditPanel.pkLabel"), pkLabelTextField = new JTextField());
    fb.append(Messages.getString("RelationshipEditPanel.fkLabel"), fkLabelTextField = new JTextField());

    JButton swapButton = new JButton(swapLabelText);
    swapButton.setIcon(
            SPSUtils.createIcon("arrow_refresh", "Swap Labels", ArchitectSwingSessionContext.ICON_SIZE));
    swapButton.setToolTipText("Swap Label Texts");
    fb.append(swapButton);
    fb.nextLine();

    identifyingGroup = new ButtonGroup();
    fb.append(Messages.getString("RelationshipEditPanel.type"), //$NON-NLS-1$
            identifyingButton = new JRadioButton(Messages.getString("RelationshipEditPanel.identifying")), 7); //$NON-NLS-1$
    identifyingGroup.add(identifyingButton);
    fb.append("", //$NON-NLS-1$
            nonIdentifyingButton = new JRadioButton(Messages.getString("RelationshipEditPanel.nonIdentifying")), //$NON-NLS-1$
            7);
    identifyingGroup.add(nonIdentifyingButton);

    fb.nextLine();
    fb.appendUnrelatedComponentsGapRow();

    pkTypeGroup = new ButtonGroup();
    fkTypeGroup = new ButtonGroup();
    fb.nextLine();
    fb.append(Messages.getString("RelationshipEditPanel.cardinality"), //$NON-NLS-1$
            pkTableName = new JLabel("PK Table: Unknown")); //$NON-NLS-1$
    fb.append("", fkTableName = new JLabel("FK Table: Unknown")); //$NON-NLS-1$ //$NON-NLS-2$
    fb.nextLine();

    fb.append("", pkTypeZeroToMany = new JRadioButton(Messages.getString("RelationshipEditPanel.zeroOrMore"))); //$NON-NLS-1$ //$NON-NLS-2$
    pkTypeGroup.add(pkTypeZeroToMany);
    fb.append("", fkTypeZeroToMany = new JRadioButton(Messages.getString("RelationshipEditPanel.zeroOrMore"))); //$NON-NLS-1$ //$NON-NLS-2$
    fkTypeGroup.add(fkTypeZeroToMany);
    fb.nextLine();

    fb.append("", pkTypeOneToMany = new JRadioButton(Messages.getString("RelationshipEditPanel.oneOrMore"))); //$NON-NLS-1$ //$NON-NLS-2$
    pkTypeGroup.add(pkTypeOneToMany);
    fb.append("", fkTypeOneToMany = new JRadioButton(Messages.getString("RelationshipEditPanel.oneOrMore"))); //$NON-NLS-1$ //$NON-NLS-2$
    fkTypeGroup.add(fkTypeOneToMany);
    fb.nextLine();

    fb.append("", pkTypeZeroOne = new JRadioButton(Messages.getString("RelationshipEditPanel.zeroOrOne"))); //$NON-NLS-1$ //$NON-NLS-2$
    pkTypeGroup.add(pkTypeZeroOne);
    fb.append("", fkTypeZeroOne = new JRadioButton(Messages.getString("RelationshipEditPanel.zeroOrOne"))); //$NON-NLS-1$ //$NON-NLS-2$
    fkTypeGroup.add(fkTypeZeroOne);
    fb.nextLine();

    fb.append("", pkTypeOne = new JRadioButton(Messages.getString("RelationshipEditPanel.exactlyOne"))); //$NON-NLS-1$ //$NON-NLS-2$
    pkTypeGroup.add(pkTypeOne);

    fb.nextLine();
    fb.appendUnrelatedComponentsGapRow();
    fb.nextLine();

    deferrabilityGroup = new ButtonGroup();
    fb.append(Messages.getString("RelationshipEditPanel.deferrability"), //$NON-NLS-1$
            notDeferrable = new JRadioButton(Messages.getString("RelationshipEditPanel.notDeferrable")), 7); //$NON-NLS-1$
    deferrabilityGroup.add(notDeferrable);
    fb.append("", //$NON-NLS-1$
            initiallyDeferred = new JRadioButton(Messages.getString("RelationshipEditPanel.initiallyDeferred")), //$NON-NLS-1$
            7);
    deferrabilityGroup.add(initiallyDeferred);
    fb.append("", initiallyImmediate = new JRadioButton( //$NON-NLS-1$
            Messages.getString("RelationshipEditPanel.initiallyImmediate")), 7); //$NON-NLS-1$
    deferrabilityGroup.add(initiallyImmediate);

    fb.nextLine();
    fb.appendUnrelatedComponentsGapRow();

    updateRuleGroup = new ButtonGroup();
    deleteRuleGroup = new ButtonGroup();
    fb.nextLine();
    fb.append(Messages.getString("RelationshipEditPanel.updateRule"), //$NON-NLS-1$
            updateCascade = new JRadioButton(Messages.getString("RelationshipEditPanel.cascade"))); //$NON-NLS-1$
    updateRuleGroup.add(updateCascade);
    fb.append(Messages.getString("RelationshipEditPanel.deleteRule"), //$NON-NLS-1$
            deleteCascade = new JRadioButton(Messages.getString("RelationshipEditPanel.cascade"))); //$NON-NLS-1$
    deleteRuleGroup.add(deleteCascade);
    fb.nextLine();

    fb.append("", updateRestrict = new JRadioButton(Messages.getString("RelationshipEditPanel.restrict"))); //$NON-NLS-1$ //$NON-NLS-2$
    updateRuleGroup.add(updateRestrict);
    fb.append("", deleteRestrict = new JRadioButton(Messages.getString("RelationshipEditPanel.restrict"))); //$NON-NLS-1$ //$NON-NLS-2$
    deleteRuleGroup.add(deleteRestrict);
    fb.nextLine();

    fb.append("", updateNoAction = new JRadioButton(Messages.getString("RelationshipEditPanel.noAction"))); //$NON-NLS-1$ //$NON-NLS-2$
    updateRuleGroup.add(updateNoAction);
    fb.append("", deleteNoAction = new JRadioButton(Messages.getString("RelationshipEditPanel.noAction"))); //$NON-NLS-1$ //$NON-NLS-2$
    deleteRuleGroup.add(deleteNoAction);
    fb.nextLine();

    fb.append("", updateSetNull = new JRadioButton(Messages.getString("RelationshipEditPanel.setNull"))); //$NON-NLS-1$ //$NON-NLS-2$
    updateRuleGroup.add(updateSetNull);
    fb.append("", deleteSetNull = new JRadioButton(Messages.getString("RelationshipEditPanel.setNull"))); //$NON-NLS-1$ //$NON-NLS-2$
    deleteRuleGroup.add(deleteSetNull);
    fb.nextLine();

    fb.append("", updateSetDefault = new JRadioButton(Messages.getString("RelationshipEditPanel.setDefault"))); //$NON-NLS-1$ //$NON-NLS-2$
    updateRuleGroup.add(updateSetDefault);
    fb.append("", deleteSetDefault = new JRadioButton(Messages.getString("RelationshipEditPanel.setDefault"))); //$NON-NLS-1$ //$NON-NLS-2$
    deleteRuleGroup.add(deleteSetDefault);
    fb.nextLine();

    setRelationship(r.getModel());

    //TODO  Doesn't work!
    relationshipName.selectAll();

    fb.setDefaultDialogBorder();
    panel = fb.getPanel();
}

From source file:ca.sqlpower.matchmaker.swingui.address.AddressValidationEntryPanel.java

License:Open Source License

private void buildUI() {
    DefaultFormBuilder builder = new DefaultFormBuilder(
            new FormLayout("fill:pref:grow,4dlu,fill:pref", "pref,4dlu,pref,4dlu,fill:pref:grow"), panel);
    builder.setDefaultDialogBorder();/*from  ww w.j a v  a2s  .  c om*/
    CellConstraints cc = new CellConstraints();

    try {
        final Address address1;

        logger.debug("ADDRESS BEFORE PARSING IS : " + addressResult.getOutputAddress());
        address1 = Address.parse(addressResult.getOutputAddress().getAddress(),
                addressResult.getOutputAddress().getMunicipality(),
                addressResult.getOutputAddress().getProvince(),
                addressResult.getOutputAddress().getPostalCode(), addressResult.getOutputAddress().getCountry(),
                addressDatabase);
        logger.debug("ADDRESS AFTER PARSING IS : " + address1);
        logger.debug("The output address is not empty.");
        logger.debug("The non-empty address is: " + address1);
        this.addressValidator = new AddressValidator(addressDatabase, address1);

        JButton saveButton = new JButton("Save");
        selectedAddressLabel = new AddressLabel(addressResult.getOutputAddress(), null, true,
                addressValidator.isAddressValid());
        selectedAddressLabel.addPropertyChangeListener(new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("currentAddress")) {
                    // update the suggestionList
                    Address address = (Address) evt.getNewValue();
                    if (address.getType() == null) { //unparsed address, needs to be parsed, This could also be a failed to parse address, won't hurt to try parsing again
                        try {
                            address = Address.parse(address.getAddress(), address.getMunicipality(),
                                    address.getProvince(), address.getPostalCode(), address.getCountry(),
                                    addressDatabase);
                        } catch (RecognitionException e) {
                            MMSUtils.showExceptionDialog(panel,
                                    "There was an error while trying to parse this address", e);
                        } catch (DatabaseException e) {
                            MMSUtils.showExceptionDialog(panel,
                                    "There was a database error while trying to parse this address", e);
                        }
                    }
                    addressValidator = new AddressValidator(addressDatabase, address);
                    suggestionList.setModel(new JList(addressValidator.getSuggestions().toArray()).getModel());
                    selectedAddressLabel.setAddressValid(addressValidator.isAddressValid());
                    updateProblemDetails();
                    save();
                }
            }
        });
        selectedAddressLabel.setFont(selectedAddressLabel.getFont()
                .deriveFont((float) (selectedAddressLabel.getFont().getSize() + 3)));

        JButton revertButton = new JButton("Revert");
        revertButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    logger.debug("Revert Address: " + addressResult.toString());
                    Address address = Address.parse(addressResult.getInputAddress().getUnparsedAddressLine1(),
                            addressResult.getInputAddress().getMunicipality(),
                            addressResult.getInputAddress().getProvince(),
                            addressResult.getInputAddress().getPostalCode(),
                            addressResult.getInputAddress().getCountry(), addressDatabase);
                    addressResult.setOutputAddress(selectedAddressLabel.getCurrentAddress());
                    selectedAddressLabel.setCurrentAddress(address);
                } catch (RecognitionException e1) {
                    e1.printStackTrace();
                } catch (DatabaseException e1) {
                    throw new RuntimeException("A database exception occurred while parsing the address" + e1);
                }
            }

        });

        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                save();
            }
        });

        //         undoButton = new JButton("Undo");

        //         redoButton = new JButton("Redo");

        JLabel suggestLabel = new JLabel("Suggestions:");
        suggestLabel.setFont(suggestLabel.getFont().deriveFont(Font.BOLD));

        problemsBuilder = new DefaultFormBuilder(new FormLayout("fill:pref:grow"));
        updateProblemDetails();
        suggestionList = new JList(addressValidator.getSuggestions().toArray());
        logger.debug("There are " + addressValidator.getSuggestions().size() + " suggestions.");
        suggestionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        suggestionList.setCellRenderer(new AddressListCellRenderer(address1, false));
        suggestionList.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                logger.debug("Mouse Clicked on suggestion list " + ((JList) e.getSource()).getSelectedValue());
                final Address selected = (Address) ((JList) e.getSource()).getSelectedValue();
                if (selected != null) {
                    //XXX:This does not update the model currently
                    selectedAddressLabel.setCurrentAddress(selected);
                }
            }
        });
        JScrollPane scrollList = new JScrollPane(suggestionList);
        scrollList.setPreferredSize(new Dimension(230, 1000));

        ButtonBarBuilder bbb = new ButtonBarBuilder();
        bbb.addRelatedGap();
        bbb.addGridded(revertButton);
        bbb.addRelatedGap();
        bbb.addGridded(saveButton);
        bbb.addRelatedGap();
        builder.add(bbb.getPanel(), cc.xy(1, 1));
        builder.add(suggestLabel, cc.xy(3, 1));
        builder.add(selectedAddressLabel, cc.xy(1, 3));
        builder.add(problemsBuilder.getPanel(), cc.xy(1, 5));
        builder.add(scrollList, cc.xywh(3, 3, 1, 3));

    } catch (RecognitionException e1) {
        MMSUtils.showExceptionDialog(getPanel(), "There was an error while trying to parse this address", e1);
    } catch (DatabaseException e1) {
        MMSUtils.showExceptionDialog(getPanel(),
                "There was a database error while trying to parse this address", e1);
    }
}

From source file:ca.sqlpower.matchmaker.swingui.address.AddressValidationEntryPanel.java

License:Open Source License

public void updateProblemDetails() {
    validateResult = addressValidator.getResults();
    logger.debug("The size of the Problems is : " + validateResult.size());
    problemsBuilder.getPanel().removeAll();
    //XXX:This recreates the panel based on the same panel.
    problemsBuilder = new DefaultFormBuilder(new FormLayout("max(400;min)"), problemsBuilder.getPanel());
    JLabel problemsHeading = new JLabel("Problems:");
    problemsHeading.setFont(new Font(null, Font.BOLD, 13));
    problemsBuilder.append(problemsHeading);
    for (ValidateResult vr : validateResult) {
        logger.debug("The Problem details are: " + vr);
        if (vr.getStatus() == Status.FAIL) {
            problemsBuilder.append(new JLabel("<html>Fail: " + vr.getMessage() + "</html>",
                    SPSUtils.createIcon("fail", "Fail"), JLabel.LEFT));
        } else if (vr.getStatus() == Status.WARN) {
            problemsBuilder.append(new JLabel("<html>Warning: " + vr.getMessage() + "</html>",
                    SPSUtils.createIcon("warn", "Warn"), JLabel.LEFT));
        }/*from ww w .  ja v a2  s.c  o m*/
    }
    problemsBuilder.getPanel().revalidate();
    problemsBuilder.getPanel().repaint();
}

From source file:ca.sqlpower.matchmaker.swingui.munge.AbstractMungeComponent.java

License:Open Source License

/**
 * Creates a AbstractMungeComponent for the given step that will be in the munge pen.
 * Sets the background and border colours to given colours.
 * //from   w w  w .  j a va2  s  .  c  o m
 * @param step The step connected to the UI
 * @param border The colour for the border around the rectangle
 * @param bg The background colour to the rectangle
 */
public AbstractMungeComponent(MungeStep step, FormValidationHandler handler, MatchMakerSession s) {
    if (step == null)
        throw new NullPointerException("Null step");

    try {
        step.refresh(logger);
    } catch (Exception e1) {
        throw new RuntimeException("Failed to refresh step " + step.getName(), e1);
    }

    this.session = (MatchMakerSwingSession) s;
    this.handler = handler;

    this.step = step;
    setVisible(true);
    setBackground(normalBackground);

    autoScrollTimer = new Timer(AUTO_SCROLL_TIME, new AbstractAction() {

        public void actionPerformed(ActionEvent e) {
            logger.debug("TIMER GO!!!");
            getPen().autoscroll(autoScrollPoint, AbstractMungeComponent.this);
        }
    });

    autoScrollTimer.stop();
    autoScrollTimer.setRepeats(true);

    dropNibIndex = -1;

    ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
    toolTipManager.setInitialDelay(0);

    bustGhost();

    mungeComKeyListener = new MungeComponentKeyListener();
    addKeyListener(mungeComKeyListener);

    step.addSPListener(new StepEventHandler());
    setName(step.getName());

    resizeBorders();

    setOpaque(false);
    setFocusable(true);

    Dimension ps = getPreferredSize();
    setBounds(0, 0, ps.width, ps.height);

    DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("pref", "pref, pref, fill:pref, pref"),
            this);
    setBackground(Color.GREEN);

    inputNames = new JPanel();
    inputNames.setOpaque(false);
    inputNames.setLayout(new FlowLayout());

    inputLabels = new CoolJLabel[step.getMSOInputs().size()];

    for (int x = 0; x < inputLabels.length; x++) {
        InputDescriptor id = step.getInputDescriptor(x);
        inputLabels[x] = new CoolJLabel(id.getName(), id.getType());
        inputLabels[x].collapse();
        inputNames.add(inputLabels[x]);
        inputLabels[x].setOpaque(false);
    }
    setInputShowNames(false);

    builder.append(inputNames);
    builder.nextLine();
    if (isExpanded() && inputNames.isVisible()) {
        inputNames.setVisible(true);
    } else {
        inputNames.setVisible(false);
    }
    revalidate();

    outputNames = new JPanel();
    outputNames.setOpaque(false);
    outputNames.setLayout(new FlowLayout());

    outputLabels = new CoolJLabel[step.getChildren(MungeStepOutput.class).size()];

    for (int x = 0; x < outputLabels.length; x++) {
        MungeStepOutput out = step.getChildren(MungeStepOutput.class).get(x);
        outputLabels[x] = new CoolJLabel(out.getName(), out.getType());
        outputLabels[x].collapse();
        outputNames.add(outputLabels[x]);
        outputLabels[x].setOpaque(false);
    }
    setOutputShowNames(false);

    JPanel tmp = new JPanel(new FlowLayout());
    tmp.setBackground(Color.BLUE);
    tmp.add(new JLabel(step.getName()));

    hideShow = new JButton(new HideShowAction());
    hideShow.setIcon(EXPOSE_OFF);

    setupOpaqueComponents();
    content = buildUI();
    //returning null will prevent the +/- button form showing up
    if (content != null) {
        deOpaquify(content);
        JToolBar tb = new JToolBar();
        hideShow.setBorder(null);
        hideShow.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                hideShow.setIcon(EXPOSE_ON);
                hideShow.setBorder(null);
            }

            public void mouseExited(MouseEvent e) {
                hideShow.setIcon(EXPOSE_OFF);
                hideShow.setBorder(null);
            }
        });

        tb.setBorder(null);
        tb.add(hideShow);
        tb.setFloatable(false);
        tmp.add(tb);
    }

    builder.append(tmp);
    builder.nextLine();
    if (content != null) {
        builder.append(content);
    }
    builder.nextLine();
    builder.append(outputNames);

    addMouseListener(new MungeComponentMouseListener());
    addMouseMotionListener(new MungeComponentMouseMoveListener());

    addComponentListener(new ComponentListener() {

        public void componentHidden(ComponentEvent e) {
        }

        public void componentMoved(ComponentEvent e) {
            getParent().repaint();
        }

        public void componentResized(ComponentEvent e) {
            getParent().repaint();
        }

        public void componentShown(ComponentEvent e) {
        }
    });

    addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            //if it is being deleted
            if (getParent() != null) {
                getParent().repaint();
                MatchMakerTreeModel treeModel = (MatchMakerTreeModel) session.getTree().getModel();

                TreePath menuPath = treeModel.getPathForNode(getStep());
                session.getTree().setSelectionPath(menuPath);
            }
        }

        public void focusLost(FocusEvent e) {
            if (getParent() != null) {
                getParent().repaint();
            }
            if (autoScrollTimer.isRunning()) {
                autoScrollTimer.stop();
            }
        }
    });

    setOpaque(false);
    tmp.setOpaque(false);

    // Note, this does not take care of the content panel; only the basic
    // stuff added here in the constructor (most importantly, the +/- button)
    deOpaquify(this);
    deOpaquify(inputNames);
    setDefaults();
}

From source file:ca.sqlpower.matchmaker.swingui.munge.GoogleAddressLookupMungeComponent.java

License:Open Source License

@Override
protected JPanel buildUI() {
    GoogleAddressLookup temp = (GoogleAddressLookup) getStep();

    url = new JTextField(temp.getGoogleGeocoderURL());
    url.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            doStuff();/*from www.j a va2s  .  c o m*/
        }

        public void removeUpdate(DocumentEvent e) {
            doStuff();
        }

        public void changedUpdate(DocumentEvent e) {
            doStuff();
        }

        private void doStuff() {
            GoogleAddressLookup step = (GoogleAddressLookup) getStep();
            step.setGoogleGeocoderURL(url.getText());
        }
    });

    key = new JTextField(temp.getGoogleMapsApiKey());
    key.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent e) {
            doStuff();
        }

        public void removeUpdate(DocumentEvent e) {
            doStuff();
        }

        public void changedUpdate(DocumentEvent e) {
            doStuff();
        }

        private void doStuff() {
            GoogleAddressLookup step = (GoogleAddressLookup) getStep();
            step.setGoogleMapsApiKey(key.getText());
        }
    });

    rateLimit = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 10.0, 0.1));
    rateLimit.setValue(temp.getRateLimit());

    JPanel mainContent = new JPanel();
    DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("fill:pref:grow", "fill:pref, pref"),
            mainContent);

    FormLayout layout = new FormLayout("4dlu,pref,4dlu,fill:pref:grow,4dlu", // columns
            "4dlu,pref,4dlu,pref,4dlu,pref,4dlu,pref,4dlu"); // rows
    CellConstraints cc = new CellConstraints();
    JPanel content = new JPanel(layout);
    content.add(new JLabel("URL:"), cc.xy(2, 2));
    content.add(url, cc.xy(4, 2));
    content.add(new JLabel("Google Maps API Key:"), cc.xy(2, 4));
    content.add(key, cc.xy(4, 4));
    content.add(new JLabel("Rate Limit (s):"), cc.xy(2, 6));
    content.add(rateLimit, cc.xy(4, 6));

    JPanel subPanel = new JPanel(new FlowLayout());
    showAllButton = new JButton(new HideShowAllLabelsAction("Show All", false, true, true));
    hideAllButton = new JButton(new HideShowAllLabelsAction("Hide All", false, true, false));
    subPanel.add(showAllButton);
    subPanel.add(hideAllButton);

    builder.append(content);
    builder.nextLine();
    builder.append(subPanel);

    return mainContent;
}

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

License:Open Source License

/**
 * Creates a new user prompter that uses a dialog to prompt the user.
 * Normally this constructor should be called via a {@link UserPrompterFactory}
 * such as the current ArchitectSession.
 *///  w ww.ja va 2  s.  com
public DialogUserPrompter(UserPromptOptions optionType, UserPromptResponse defaultResponseType, JFrame owner,
        String questionMessage, boolean modal, String... buttonNames) {
    if (optionType.getButtonCount() != buttonNames.length) {
        throw new IllegalStateException(
                "Expecting " + optionType.getButtonCount() + " arguments for the optionType " + optionType
                        + "Recieved 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
    //Using JEditorPane for html messages as JTextAreas do not respect html tags.
    //Using JTextArea for the rest of the messages as JEditorPane does not support
    //new line characters and to keep font consistent.
    if (questionMessage.startsWith("<html>")) {
        questionField = new JEditorPane();
        questionField.setText(questionMessage);
        ((JEditorPane) questionField).setContentType("text/html");
        questionField.setFont(new JTextArea().getFont());
    } else {
        questionField = new JTextArea(questionMessage);
    }
    questionField.setEditable(false);
    questionField.setBackground(null);

    questionFormat = new MessageFormat(questionMessage);

    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.swingui.LabelEditorPanel.java

License:Open Source License

public LabelEditorPanel(SPLabel label, boolean variables) {
    this.label = label;
    panel = new JPanel();
    final DefaultFormBuilder fb = new DefaultFormBuilder(
            new FormLayout("pref, 4dlu, pref, 4dlu, pref, 4dlu, pref, 4dlu, 100dlu:grow"), panel);
    fb.getLayout().setColumnGroups(new int[][] { { 1, 5 }, { 3, 7 } });

    textArea = new JTextPane();
    textArea.setText(label.getText());//from   w w  w.j av  a  2  s .co  m

    JButton variableButton = null;
    if (variables) {
        VariableLabel.insertLabels(getVariablesHelper(), textArea.getDocument(), textArea);

        Action insertVariableAction = new InsertVariableAction("Variables", getVariablesHelper(), null,
                new VariableInserter() {
                    public void insert(String variable) {
                        try {
                            VariableLabel.insertLabel(
                                    variable.replaceFirst("\\$", "").replaceFirst("\\{", "").replaceFirst("\\}",
                                            ""),
                                    getVariablesHelper(), textArea.getDocument(), textArea.getCaretPosition(),
                                    textArea);
                        } catch (BadLocationException e) {
                            throw new IllegalStateException(e);
                        }
                    }
                }, textArea);

        variableButton = new JButton("Variables");
        variableButton.setAction(insertVariableAction);

        // Maps CTRL+SPACE to insert variable
        textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.CTRL_MASK),
                "insertVariable");
        textArea.getActionMap().put("insertVariable", insertVariableAction);

    }

    ButtonGroup hAlignmentGroup = new ButtonGroup();
    leftAlign = new JToggleButton(AlignmentIcons.LEFT_ALIGN_ICON,
            label.getHorizontalAlignment() == HorizontalAlignment.LEFT);
    hAlignmentGroup.add(leftAlign);
    centreAlign = new JToggleButton(AlignmentIcons.CENTRE_ALIGN_ICON,
            label.getHorizontalAlignment() == HorizontalAlignment.CENTER);
    hAlignmentGroup.add(centreAlign);
    rightAlign = new JToggleButton(AlignmentIcons.RIGHT_ALIGN_ICON,
            label.getHorizontalAlignment() == HorizontalAlignment.RIGHT);
    hAlignmentGroup.add(rightAlign);

    ButtonGroup vAlignmentGroup = new ButtonGroup();
    topAlign = new JToggleButton(AlignmentIcons.TOP_ALIGN_ICON,
            label.getVerticalAlignment() == VerticalAlignment.TOP);
    vAlignmentGroup.add(topAlign);
    middleAlign = new JToggleButton(AlignmentIcons.MIDDLE_ALIGN_ICON,
            label.getVerticalAlignment() == VerticalAlignment.MIDDLE);
    vAlignmentGroup.add(middleAlign);
    bottomAlign = new JToggleButton(AlignmentIcons.BOTTOM_ALIGN_ICON,
            label.getVerticalAlignment() == VerticalAlignment.BOTTOM);
    vAlignmentGroup.add(bottomAlign);

    Box alignmentBox = Box.createHorizontalBox();
    alignmentBox.add(leftAlign);
    alignmentBox.add(centreAlign);
    alignmentBox.add(rightAlign);
    alignmentBox.add(Box.createHorizontalStrut(5));
    alignmentBox.add(topAlign);
    alignmentBox.add(middleAlign);
    alignmentBox.add(bottomAlign);
    if (variables) {
        alignmentBox.add(Box.createHorizontalGlue());
        alignmentBox.add(variableButton);
    }

    fb.append("Alignment", alignmentBox, 7);
    fb.appendRelatedComponentsGapRow();
    fb.appendRow("pref");
    fb.nextLine(2);

    bgColor = new JComboBox(ColourScheme.BACKGROUND_COLOURS);
    fb.append("Label Colour", bgColor);
    ColorCellRenderer renderer = new ColorCellRenderer(40, 20);
    bgColor.setRenderer(renderer);
    bgColor.setSelectedItem(label.getBackgroundColour());
    if (label.getBackgroundColour() == null) {
        bgColor.setSelectedIndex(0);
    }
    bgColor.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            bgIsNull.setSelected(false);
        }
    });

    bgIsNull = new JCheckBox("Transparent", label.getBackgroundColour() == null);
    fb.append(bgIsNull);
    fb.appendRelatedComponentsGapRow();
    fb.appendRow("pref");
    fb.nextLine(2);

    fgColor = new JComboBox(ColourScheme.FOREGROUND_COLOURS);
    fb.append("Text Colour", fgColor);
    fgColor.setRenderer(renderer);
    fgColor.setSelectedItem(label.getForegroundColour());

    fb.appendRelatedComponentsGapRow();
    fb.appendRow("pref");
    fb.nextLine(2);

    bdColor = new JComboBox(ColourScheme.FOREGROUND_COLOURS);
    fb.append("Border Colour", bdColor);
    bdColor.setRenderer(renderer);
    bdColor.setSelectedItem(label.getBorderColour());
    if (label.getBorderColour() == null) {
        bdColor.setSelectedIndex(0);
    }
    bdColor.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            borderIsNull.setSelected(false);
        }
    });

    borderIsNull = new JCheckBox("No Border", label.getBorderColour() == null);
    fb.append(borderIsNull);

    fb.appendRelatedComponentsGapRow();
    fb.appendRow("fill:90dlu:grow");
    fb.nextLine(2);

    textArea.setFont(label.getFont());
    JLabel textLabel = fb.append("Text", new JScrollPane(textArea), 7);
    textLabel.setVerticalTextPosition(JLabel.TOP);
    fb.appendRow("pref");
    fb.nextLine();

    fontSelector = getFontSelector();
    if (fontSelector != null) {
        logger.debug("FontSelector got passed Font " + label.getFont());
        fontSelector.setShowingPreview(false);
        fontSelector.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                logger.debug("Changing font to: " + fontSelector.getSelectedFont());
                textArea.setFont(fontSelector.getSelectedFont());
            }
        });
        fb.append("Font", fontSelector.getPanel(), 5);
    }

}

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);//from   www .ja va2  s. co 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  .jav a  2 s.  c  o m*/
 * @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.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 av  a 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());
}