Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
   *
   * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
   * Other names may be trademarks of their respective owners.
   *
   * The contents of this file are subject to the terms of either the GNU
  * General Public License Version 2 only ("GPL") or the Common
  * Development and Distribution License("CDDL") (collectively, the
  * "License"). You may not use this file except in compliance with the
  * License. You can obtain a copy of the License at
  * http://www.netbeans.org/cddl-gplv2.html
  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  * specific language governing permissions and limitations under the
  * License.  When distributing the software, include this License Header
  * Notice in each file and include the License file at
  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the GPL Version 2 section of the License file that
  * accompanied this code. If applicable, add the following below the
  * License Header, with the fields enclosed by brackets [] replaced by
  * your own identifying information:
  * "Portions Copyrighted [year] [name of copyright owner]"
  *
  * If you wish your version of this file to be governed by only the CDDL
  * or only the GPL Version 2, indicate your decision by adding
  * "[Contributor] elects to include this software in this distribution
  * under the [CDDL or GPL Version 2] license." If you do not indicate a
  * single choice of license, a recipient has the option to distribute
  * your version of this file under either the CDDL, the GPL Version 2 or
  * to extend the choice of license to its licensees as provided above.
  * However, if you add GPL Version 2 code and therefore, elected the GPL
  * Version 2 license, then the option applies only if the new code is
  * made subject to such option by the copyright holder.
  *
  * Contributor(s):
  *
  * Portions Copyrighted 2009 Sun Microsystems, Inc.
  */
 
 package org.netbeans.modules.bugtracking.ui.selectors;
 
 import java.util.List;
 import  org.jdesktop.layout.LayoutStyle;
 import static javax.swing.JComponent.LEFT_ALIGNMENT;
 import static javax.swing.BoxLayout.X_AXIS;
 import static javax.swing.BoxLayout.Y_AXIS;
 import static javax.swing.SwingConstants.EAST;
 import static javax.swing.SwingConstants.HORIZONTAL;
 import static javax.swing.SwingConstants.NORTH;
 import static javax.swing.SwingConstants.SOUTH;
 import static javax.swing.SwingConstants.VERTICAL;
 import static javax.swing.SwingConstants.WEST;
 import static org.jdesktop.layout.LayoutStyle.RELATED;
 import static org.jdesktop.layout.LayoutStyle.UNRELATED;

Allows the user to select an existing connection to a bug-tracking repository or to create a new connection.

Author(s):
Marian Petras
 
 public final class RepositorySelectorBuilder implements ItemListener,
                                                         ItemSelectable {
                                                               
 
     private static final String EMPTY_PANEL = "empty panel";            //NOI18N
     private static final String NEW_REPO_PANEL = "new repo panel";      //NOI18N
    private Repository[] existingRepositories;
    private JLabel label;
    private JComboBox combo;
    private final JComponent cardsPanel;
    private boolean emptyPanelInitialized;
    private boolean isValidData;
    private boolean repositoryFormVisible;
    private ChangeEvent changeEvent;
    public RepositorySelectorBuilder() {
         = new JPanel(new CardLayout());
    }
    private String labelText = null;
    private boolean labelAbove = false;
    private boolean labelVisible = true;
    private boolean comboVisible = true;
    private boolean displayFormForExistingRepo = true;
    private String initialErrorMessage;
    private Repository repoToPreselect;
    /* SETTERS */
    public void setLabelVisible(boolean visible) {
        if (!visible && ( != null)) {
            throw new IllegalStateException(
                  "Cannot change visibility of an already created label."); //NOI18N
        }
         = visible;
    }
    public void setLabelText(String text) {
        if ( == null) {
             = text;
        } else {
            Mnemonics.setLocalizedText(text);
        }
    }
    public void setComboBoxVisible(boolean visible) {
        if (!visible && ( != null)) {
            throw new IllegalStateException(
                  "Cannot change parameters of an already created combo-box."); //NOI18N
        }
         = visible;
        if (!visible) {
             = null;
        }
    }
    public void setBugtrackingConnectorDisplayFormat(String format) {
        this. = format;
    }
    public void setLabelAboveComboBox() {
         = true;
    }
    public void setLabelNextToComboBox() {
         = false;
    }
    public void setDisplayFormForExistingRepositories(boolean display) {
         = display;
    }
    public void setExistingRepositories(Repository[] repositories) {
        if ( != null) {
            throw new IllegalStateException(
                  "Cannot change parameters of an already created combo-box."); //NOI18N
        }
        if ((repositories != null) && (repositories.length == 0)) {
            repositories = null;
        }
        this. = repositories;
    }
    public void setBugtrackingConnectors(BugtrackingConnector[] connectors) {
        if ( != null) {
            throw new IllegalStateException(
                  "Cannot change parameters of an already created combo-box."); //NOI18N
        }
        if ((connectors != null) && (connectors.length == 0)) {
            connectors = null;
        }
        this. = connectors;
    }
    public void setPreselectedRepository(Repository repository) {
         = repository;
        if ( != null) {
            .setSelectedItem(repository);
        }
    }
    public void setInitialErrorMessage(String errMsg) {
        this. = errMsg;
    }
    /* GETTERS */
    public JLabel getLabel() {
        if ( && ( == null)) {
            initializeLabel();
        }
        return ;
    }
    public JComboBox getComboBox() {
        if ( && ( == null)) {
            initializeCombo();
        }
        return ;
    }
    public JComponent getFormPanel() {
        if (!
                && ( == null)
                && ( != null)) {
            initializeCardsPanel();
        }
        return ;
    }
    /* CREATE PANEL */
    private void initializeLabel() {
         = new JLabel();
        Mnemonics.setLocalizedText(,
                                   ( != null) ?  : getDefaultLabelText());
        if ( != null) {
            bindLabelToCombo();
        }
    }
    private void initializeCombo() {
        boolean hasExistingRepositories = ( != null)
                                          && (. != 0);
        boolean hasBugtrackingConnectors = ( != null)
                                           && (. != 0);
        if (!hasExistingRepositories && !hasBugtrackingConnectors) {
            throw new IllegalStateException("No data for the combo-box."); //NOI18N
        }
        String newConnectionFormatString
                    = ( != null)
                      ? 
                      : NbBundle.getMessage(
                                ComboItemsRenderer.class,
                                "NewBugtrackingRepositoryConnection");  //NOI18N
                                         createRepositoryInfos()));
                                                 newConnectionFormatString));
        //combo.setEditable(false);
        if ( != null) {
            .setSelectedItem();
        }
        .addItemListener(this);
        .getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(RepositorySelectorBuilder.class"RepositorySelectorBuilder.combo.accessibleDescription")); // NOI18N
        if ( != null) {
            bindLabelToCombo();
        }
    }
    private void initializeCardsPanel() {
        if (!
                && ( == null)
                && ( != null)) {
        }
    }
    private void bindLabelToCombo() {
        if (( != null) && ( != null)) {
            .setLabelFor();
        }
    }
    public JComponent createPanel() {
         = getLabel();
         = getComboBox();
        initializeCardsPanel();
        if (( == null) && ( == null)) {
            addInsetsToPanel();
            return ;
        }
        JComponent upperPanel;
        if (( != null) && ( != null) && ) {
            upperPanel = new JPanel();
            upperPanel.setLayout(new BoxLayout(upperPanel));
            upperPanel.add();
            upperPanel.add(createVerticalStrut(upperPanel, RELATED));
            upperPanel.add();
            .setAlignmentX();
            .setAlignmentX();
        } else if (( != null) && ( != null)) {
            upperPanel = new JPanel();
            upperPanel.setLayout(new BoxLayout(upperPanel));
            upperPanel.add();
            upperPanel.add(createHorizontalStrut(upperPanel, RELATED));
            upperPanel.add();
        } else if ( != null) {
            upperPanel = ;
        } else {
            assert ( != null);
            upperPanel = ;
        }
        AutoResizingPanel panel = new AutoResizingPanel();
        panel.setLayout(new BorderLayout(0, getSpace(panel,
                                                     upperPanel,
                                                     ,
                                                     UNRELATED,
                                                     )));
        panel.add(upperPanel.);
        panel.add(.);
        panel.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(RepositorySelectorBuilder.class"RepositorySelector.accessibleDescription")); // NOI18N
        addInsetsToPanel(panel);
        addResizeListener(panel);
        return panel;
    }
        return new ValidatingDialogDescriptor(title);
    }
    private final class ValidatingDialogDescriptor extends DialogDescriptor
                                                   implements ChangeListener,
                                                              ItemListener {
        ValidatingDialogDescriptor(String title) {
            super(createPanel(), title);
            RepositorySelectorBuilder.this.addChangeListener(this);
            updateStatus();
            RepositorySelectorBuilder.this.addItemListener(this);
            updateHelpId();
        }
        public void stateChanged(ChangeEvent e) {
            updateStatus();
        }
        private void updateStatus() {
            setValid(RepositorySelectorBuilder.this.isValidData());
        }
        public void itemStateChanged(ItemEvent e) {
            updateHelpId();
        }
        private void updateHelpId() {
        }
        private HelpCtx getHelpFor(Repository repository) {
            return (repository != null)
                   ? repository.getController().getHelpCtx()
                   : null;
        }
    }
    private final class AutoResizingPanel extends JPanel
                                          implements ResizeListener {
        AutoResizingPanel() {
            super();
        }
        AutoResizingPanel(LayoutManager lm) {
            super(lm);
        }
        private Dimension requestedSize;
        public void resizeMayBeNeeded() {
            expandWindowToFitNewConnectorForm();
        }
        private void expandWindowToFitNewConnectorForm() {
            Window window = SwingUtilities.getWindowAncestor(this);
            if (window == null) {
                return;
            }
            Dimension currSize = getSize();
            Dimension prefSize = getPreferredSize();
            if ((currSize.width >= prefSize.width) && (currSize.height >= prefSize.height)) {
                /* the dialog is large enough to fit the form */
                return;
            }
            try {
                 = new Dimension(
                                        Math.max(currSize.widthprefSize.width),
                                        Math.max(currSize.heightprefSize.height));
                window.pack();
            } finally {
                 = null;
            }
        }
        @Override
        public Dimension getPreferredSize() {
            return ( != null) ? 
                                           : super.getPreferredSize();
        }
    }
    /* PRIVATE METHODS */
    private static NewRepositoryInfo[] createRepositoryInfos(
                                            BugtrackingConnector[] connectors) {
        if (connectors == null) {
            return null;
        }
        NewRepositoryInfo[] result = new NewRepositoryInfo[connectors.length];
        for (int i = 0; i < connectors.lengthi++) {
            result[i] = new NewRepositoryInfo(connectors[i]);
        }
        return result;
    }
    public Repository getSelectedRepository() {
        if ( != null) {
            Object selectedItem = .getSelectedItem();
            if (selectedItem instanceof Repository) {
                return (RepositoryselectedItem;
            }
        }
    }
    public boolean isValidData() {
        return ;
    }
    private static String getDefaultLabelText() {
        return getText("LBL_SelectBugtrackingRepository");              //NOI18N
    }
    private static void addInsetsToPanel(JComponent comp) {
        LayoutStyle layoutStyle = LayoutStyle.getSharedInstance();
        comp.setBorder(BorderFactory.createEmptyBorder(
                layoutStyle.getContainerGap(compnull),
                layoutStyle.getContainerGap(comp,  null),
                layoutStyle.getContainerGap(compnull),
                layoutStyle.getContainerGap(comp,  null)));
    }
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == .) {
            itemSelected(e.getItem());
        }
    }
    private void itemSelected(Object selectedItem) {
        if (selectedItem instanceof NewRepositoryInfo) {
            NewRepositoryInfo newRepoInfo = (NewRepositoryInfoselectedItem;
            displayRepositoryForm(newRepoInfo);
        } else {
            assert selectedItem instanceof Repository;
            if () {
                Repository repository = (RepositoryselectedItem;
                displayRepositoryForm(repository);
            } else {
                displayEmptyPanel();
            }
        }
        fireSelectionChanged();
    }
    private void setDataValid(boolean valid) {
        boolean wasValid = ;
         = valid;
        if ( != wasValid) {
            fireDataValidityChanged();
        }
    }
    private void displayEmptyPanel() {
        if (!) {
            .add(new JPanel(), );
             = true;
        }
        if () {
             = false;
        }
        setDataValid(true);
    }
    private void displayRepositoryForm(NewRepositoryInfo newRepoInfo) {
        if (newRepoInfo.repository == null) {
            newRepoInfo.initializeRepository();
        }
        displayRepositoryForm(newRepoInfo.repository);
    }
    public void displayRepository(Repository repository) {
        boolean selectedInCombo;
        if ( != null) {
            .setSelectedItem(repository);
            selectedInCombo = (.getSelectedItem() == repository);
        } else {
            selectedInCombo = false;
        }
        if (!selectedInCombo) {
            displayRepositoryForm(repository);
        }
    }
    public void displayRepositoryForm(Repository repository) {
        displayRepositoryForm(repositorynull);
    }
    public void displayRepositoryForm(Repository repositoryString initialErrMsg) {
        boolean wasRepositoryFormVisible = ;
        boolean firstUsed = .displayForm(repositoryinitialErrMsg);
        if (!wasRepositoryFormVisible) {
             = true;
        }
        if (firstUsed) {
            notifyResizeListeners();
        }
    }
    private void makeSureRepositoryFormsPanelExists() {
        if ( != null) {
            return;
        }
         = new RepositoryFormPanel();
        if ( != null) {
        }
        if ( == null) {
             = new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    setDataValid(.isValidData());
                }
            };
        }
    }
    private void fireDataValidityChanged() {
        if (( != null) && !.isEmpty()) {
            if ( == null) {
                 = new ChangeEvent(this);
            }
            for (ChangeListener l : ) {
                l.stateChanged();
            }
        }
    }
    public void addChangeListener(ChangeListener listener) {
        if ( == null) {
             = new ArrayList<ChangeListener>(4);
        }
        .add(listener);
    }
    public void removeChangeListener(ChangeListener listener) {
        if ( == null) {
            return;
        }
        .remove(listener);
    }
    public void addItemListener(ItemListener listener) {
        if ( == null) {
             = new ArrayList<ItemListener>(2);
        }
        .add(listener);
    }
    public void removeItemListener(ItemListener listener) {
        if ( == null) {
            return;
        }
        .remove(listener);
    }
    public Object[] getSelectedObjects() {
        Repository selectedRepo = getSelectedRepository();
        return (selectedRepo != null) ? new Repository[] {selectedRepo}
                                      : null;
    }
    private void fireSelectionChanged() {
        if (( == null) || .isEmpty()) {
            return;
        }
        final ItemEvent event = new ItemEvent(this,
                                              .,
                                              getSelectedRepository(),
                                              .);
        for (ItemListener l : ) {
            l.itemStateChanged(event);
        }
    }
    public interface ResizeListener {
        void resizeMayBeNeeded();
    }
    public void addResizeListener(ResizeListener l) {
        if ( == null) {
             = new ArrayList<ResizeListener>(4);
        }
        .add(l);
    }
    public void removeResizeListener(ResizeListener l) {
        if ( == null) {
            return;
        }
        .remove(l);
    }
    private void notifyResizeListeners() {
        if (( != null) && !.isEmpty()) {
            for (ResizeListener l : ) {
                l.resizeMayBeNeeded();
            }
        }
    }
    private static String getText(String msgKey) {
        return NbBundle.getMessage(RepositorySelectorBuilder.classmsgKey);
    }
    private Component createHorizontalStrut(JComponent parentJComponent compAJComponent compBint related) {
        return Box.createHorizontalStrut(getSpace(parentcompAcompBrelated));
    }
    private Component createVerticalStrut(JComponent parentJComponent compAJComponent compBint related) {
        return Box.createVerticalStrut(getSpace(parentcompAcompBrelated));
    }
    private int getSpace(JComponent parentJComponent compAJComponent compBint relatedint horizontal) {
        return LayoutStyle.getSharedInstance()
               .getPreferredGap(compA,
                                compB,
                                related,
                                (horizontal == ) ?  : ,
                                parent);
    }
    private static Object[] joinArrays(Object[] array1Object[] array2) {
        if ((array1 == null) || (array1.length == 0)) {
            return array2;
        }
        if ((array2 == null) || (array2.length == 0)) {
            return array1;
        }
        Object[] result = new Object[array1.length + array2.length];
        System.arraycopy(array1, 0, result,             0, array1.length);
        System.arraycopy(array2, 0, resultarray1.lengtharray2.length);
        return result;
    }
    private static final class NewRepositoryInfo {
        private final BugtrackingConnector connector;
        private Repository repository;
        private NewRepositoryInfo(BugtrackingConnector connector) {
            this. = connector;
        }
        Repository initializeRepository() {
            assert  == null;
             = .createRepository();
            return ;
        }
            }
    private static final class ComboItemsRenderer implements ListCellRenderer {
        /*
         * Not extending the DefaultListCellRenderer due to JDK bug.
         * Doing so would break rendering of a combo-box in GTK L&F.
         */
        private final MessageFormat newConnectionFormat;
        private final ListCellRenderer defaultRenderer;
        private ComboItemsRenderer(ListCellRenderer defaultRenderer,
                                   String newConnectionFormatString) {
            this. = defaultRenderer;
             = new MessageFormat(newConnectionFormatString);
        }
        @Override
        public Component getListCellRendererComponent(JList list,
                                                      Object value,
                                                      int index,
                                                      boolean isSelected,
                                                      boolean cellHasFocus) {
            String text;
            if (value == null) {
                text = null;
            } else if (value instanceof Repository) {
                text = ((Repositoryvalue).getDisplayName();
            } else if (value instanceof NewRepositoryInfo) {
                String connectorName = ((NewRepositoryInfovalue).
                                       .getDisplayName();
                text = .format(new Object[] {connectorName});
            } else {
                assert false;
                text = "???";                                           //NOI18N
            }
            return .getListCellRendererComponent(list,
                                                                text,
                                                                index,
                                                                isSelected,
                                                                cellHasFocus);
        }
    }