Example usage for javax.swing JRadioButton JRadioButton

List of usage examples for javax.swing JRadioButton JRadioButton

Introduction

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

Prototype

public JRadioButton(String text) 

Source Link

Document

Creates an unselected radio button with the specified text.

Usage

From source file:com.codeasylum.liquibase.Liquidate.java

public Liquidate() {

    super("Liquidate");

    ParaboxLayoutManager layout;/*from ww w  .  j  a  v  a  2  s  .  co  m*/
    ParallelBox goalHorizontalBox;
    SerialBox sourceHorizontalBox;
    ParallelBox sourceVerticalBox;
    SerialBox goalVerticalBox;
    JSeparator buttonSeparator;
    JRadioButton[] sourceButtons;
    JRadioButton[] goalButtons;
    JLabel databaseLabel;
    JLabel hostLabel;
    JLabel colonLabel;
    JLabel schemaLabel;
    JLabel userLabel;
    JLabel passwordLabel;
    JLabel sourceLabel;
    JLabel goalLabel;
    JLabel outputLabel;
    int sourceIndex = 0;
    int goalIndex = 0;

    config = new LiquidateConfig();

    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setLayout(layout = new ParaboxLayoutManager(getContentPane()));

    databaseLabel = new JLabel("Database:");
    databaseCombo = new JComboBox(Database.values());
    databaseCombo.addItemListener(this);

    hostLabel = new JLabel("Host and Port:");
    hostTextField = new JTextField();
    hostTextField.getDocument().addDocumentListener(this);

    portTextField = new JTextField();
    portTextField.setHorizontalAlignment(JTextField.RIGHT);
    portTextField.setPreferredSize(new Dimension(50, (int) portTextField.getPreferredSize().getHeight()));
    portTextField.setMaximumSize(portTextField.getPreferredSize());
    portTextField.getDocument().addDocumentListener(this);
    colonLabel = new JLabel(":");

    schemaLabel = new JLabel("Schema:");
    schemaTextField = new JTextField();
    schemaTextField.getDocument().addDocumentListener(this);

    userLabel = new JLabel("User:");
    userTextField = new JTextField();
    userTextField.getDocument().addDocumentListener(this);

    passwordLabel = new JLabel("Password:");
    passwordField = new JPasswordField();
    passwordField.getDocument().addDocumentListener(this);

    sourceLabel = new JLabel("Change Log:");
    sourceButtonGroup = new EventCoalescingButtonGroup();
    sourceButtons = new JRadioButton[Source.values().length];
    for (Source source : Source.values()) {
        sourceButtonGroup.add(sourceButtons[sourceIndex] = new JRadioButton(
                StringUtilities.toDisplayCase(source.name(), '_')));
        sourceButtons[sourceIndex++].setActionCommand(source.name());
    }
    sourceButtons[0].setSelected(true);
    sourceButtonGroup.addActionListener(this);

    changeLogTextField = new JTextField();
    changeLogTextField.getDocument().addDocumentListener(this);

    goalLabel = new JLabel("Goal:");
    goalButtonGroup = new EventCoalescingButtonGroup();
    goalButtons = new JRadioButton[Goal.values().length - 1];
    for (Goal goal : Goal.values()) {
        if (!goal.equals(Goal.NONE)) {
            goalButtonGroup.add(
                    goalButtons[goalIndex] = new JRadioButton(StringUtilities.toDisplayCase(goal.name(), '_')));
            goalButtons[goalIndex++].setActionCommand(goal.name());
        }
    }
    goalButtons[0].setSelected(true);
    goalButtonGroup.addActionListener(this);

    outputLabel = new JLabel("Output:");
    browseButton = new JButton("Browse...", BROWSE_ICON);
    browseButton.setMargin(new Insets(2, 2, 2, 2));
    browseButton.setFocusable(false);
    browseButton.setToolTipText("browse for a file");
    browseButton.addActionListener(this);
    browseButton.setEnabled(false);
    outputTextField = new JTextField();
    outputTextField.getDocument().addDocumentListener(this);
    outputTextField.setEnabled(false);

    buttonSeparator = new JSeparator(JSeparator.HORIZONTAL);
    buttonSeparator.setMaximumSize(
            new Dimension(Integer.MAX_VALUE, (int) buttonSeparator.getPreferredSize().getHeight()));

    startButton = new JButton("Start");
    startButton.addActionListener(this);

    layout.setHorizontalBox(layout.parallelBox().add(layout.sequentialBox()
            .add(layout.parallelBox(Alignment.TRAILING).add(databaseLabel).add(hostLabel).add(schemaLabel)
                    .add(userLabel).add(passwordLabel).add(sourceLabel).add(goalLabel).add(outputLabel))
            .add(goalHorizontalBox = layout.parallelBox().add(databaseCombo, Constraint.expand())
                    .add(layout.sequentialBox(3).add(hostTextField, Constraint.expand()).add(colonLabel)
                            .add(portTextField))
                    .add(schemaTextField, Constraint.expand()).add(userTextField, Constraint.expand())
                    .add(passwordField, Constraint.expand()).add(sourceHorizontalBox = layout.sequentialBox())
                    .add(changeLogTextField, Constraint.expand())
                    .add(layout.parallelBox(Alignment.TRAILING).add(outputTextField, Constraint.expand())
                            .add(browseButton))))
            .add(buttonSeparator, Constraint.expand())
            .add(layout.sequentialBox(Justification.LAST, true).add(startButton)));

    for (JRadioButton sourceButton : sourceButtons) {
        sourceHorizontalBox.add(sourceButton);
    }

    for (JRadioButton goalButton : goalButtons) {
        goalHorizontalBox.add(goalButton);
    }

    layout.setVerticalBox(layout.sequentialBox()
            .add(layout.sequentialBox()
                    .add(layout.parallelBox(Alignment.BASELINE).add(databaseLabel).add(databaseCombo))
                    .add(layout.parallelBox(Alignment.BASELINE).add(hostLabel).add(hostTextField)
                            .add(colonLabel).add(portTextField))
                    .add(layout.parallelBox(Alignment.BASELINE).add(schemaLabel).add(schemaTextField))
                    .add(layout.parallelBox(Alignment.BASELINE).add(userLabel).add(userTextField))
                    .add(layout.parallelBox(Alignment.BASELINE).add(passwordLabel).add(passwordField)))
            .add(layout.sequentialBox(3)
                    .add(layout.parallelBox(Alignment.CENTER).add(sourceLabel)
                            .add(sourceVerticalBox = layout.parallelBox()))
                    .add(changeLogTextField))
            .add(goalVerticalBox = layout.sequentialBox(Gap.NONE)
                    .add(layout.parallelBox(Alignment.BASELINE).add(goalLabel).add(goalButtons[0]))));

    for (JRadioButton sourceButton : sourceButtons) {
        sourceVerticalBox.add(sourceButton);
    }

    for (int count = 1; count < goalButtons.length; count++) {
        goalVerticalBox.add(goalButtons[count]);
    }

    layout.getVerticalBox()
            .add(layout.sequentialBox(Gap.RELATED)
                    .add(layout.parallelBox(Alignment.BASELINE).add(outputLabel).add(outputTextField))
                    .add(browseButton))
            .add(layout.sequentialBox(Gap.RELATED).add(buttonSeparator).add(startButton));

    setSize(new Dimension(((int) getLayout().preferredLayoutSize(this).getWidth()) + 150,
            ((int) getLayout().preferredLayoutSize(this).getHeight()) + 50));
    setResizable(false);
    setLocationByPlatform(true);
}

From source file:com.google.code.facebook.graph.sna.applet.RadialTreeLensDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoomand hyperbolic features.
 * /*from www. j a  v  a2 s.  co m*/
 */
public RadialTreeLensDemo() {

    // create a simple graph for the demo
    // create a simple graph for the demo
    graph = new DelegateForest<String, Integer>();

    createTree();

    layout = new TreeLayout<String, Integer>(graph);
    radialLayout = new RadialTreeLayout<String, Integer>(graph);
    radialLayout.setSize(new Dimension(600, 600));

    Dimension preferredSize = new Dimension(600, 600);

    final VisualizationModel<String, Integer> visualizationModel = new DefaultVisualizationModel<String, Integer>(
            radialLayout, preferredSize);
    vv = new VisualizationViewer<String, Integer>(visualizationModel, preferredSize);

    PickedState<String> ps = vv.getPickedVertexState();
    PickedState<Integer> pes = vv.getPickedEdgeState();
    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<String>(ps, Color.red, Color.yellow));
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<Integer>(pes, Color.black, Color.cyan));
    vv.setBackground(Color.white);

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<String>());

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();

    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(graphMouse.getModeKeyListener());
    rings = new Rings();
    vv.addPreRenderPaintable(rings);

    hyperbolicViewSupport = new ViewLensSupport<String, Integer>(vv,
            new HyperbolicShapeTransformer(vv,
                    vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)),
            new ModalLensGraphMouse());

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    final JRadioButton hyperView = new JRadioButton("Hyperbolic View");
    hyperView.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            hyperbolicViewSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });

    graphMouse.addItemListener(hyperbolicViewSupport.getGraphMouse().getModeListener());

    JMenuBar menubar = new JMenuBar();
    menubar.add(graphMouse.getModeMenu());
    gzsp.setCorner(menubar);

    JPanel controls = new JPanel();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    JPanel hyperControls = new JPanel(new GridLayout(3, 2));
    hyperControls.setBorder(BorderFactory.createTitledBorder("Examiner Lens"));
    zoomControls.add(plus);
    zoomControls.add(minus);
    JPanel modeControls = new JPanel(new BorderLayout());
    modeControls.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    modeControls.add(graphMouse.getModeComboBox());
    hyperControls.add(hyperView);

    controls.add(zoomControls);
    controls.add(hyperControls);
    controls.add(modeControls);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:edu.uci.ics.jung.samples.RadialTreeLensDemo.java

/**
 * create an instance of a simple graph with controls to
 * demo the zoomand hyperbolic features.
 * //w ww  . j  a v a  2 s .  c o m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public RadialTreeLensDemo() {

    // create a simple graph for the demo
    // create a simple graph for the demo
    graph = new DelegateForest<String, Integer>();

    createTree();

    layout = new TreeLayout<String, Integer>(graph);
    radialLayout = new RadialTreeLayout<String, Integer>(graph);
    radialLayout.setSize(new Dimension(600, 600));

    Dimension preferredSize = new Dimension(600, 600);

    final VisualizationModel<String, Integer> visualizationModel = new DefaultVisualizationModel<String, Integer>(
            radialLayout, preferredSize);
    vv = new VisualizationViewer<String, Integer>(visualizationModel, preferredSize);

    PickedState<String> ps = vv.getPickedVertexState();
    PickedState<Integer> pes = vv.getPickedEdgeState();
    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<String>(ps, Color.red, Color.yellow));
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<Integer>(pes, Color.black, Color.cyan));
    vv.setBackground(Color.white);

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());

    // add a listener for ToolTips
    vv.setVertexToolTipTransformer(new ToStringLabeller<String>());

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();

    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(graphMouse.getModeKeyListener());
    rings = new Rings();
    vv.addPreRenderPaintable(rings);

    hyperbolicViewSupport = new ViewLensSupport<String, Integer>(vv,
            new HyperbolicShapeTransformer(vv,
                    vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW)),
            new ModalLensGraphMouse());

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    final JRadioButton hyperView = new JRadioButton("Hyperbolic View");
    hyperView.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            hyperbolicViewSupport.activate(e.getStateChange() == ItemEvent.SELECTED);
        }
    });

    graphMouse.addItemListener(hyperbolicViewSupport.getGraphMouse().getModeListener());

    JMenuBar menubar = new JMenuBar();
    menubar.add(graphMouse.getModeMenu());
    gzsp.setCorner(menubar);

    JPanel controls = new JPanel();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    JPanel hyperControls = new JPanel(new GridLayout(3, 2));
    hyperControls.setBorder(BorderFactory.createTitledBorder("Examiner Lens"));
    zoomControls.add(plus);
    zoomControls.add(minus);
    JPanel modeControls = new JPanel(new BorderLayout());
    modeControls.setBorder(BorderFactory.createTitledBorder("Mouse Mode"));
    modeControls.add(graphMouse.getModeComboBox());
    hyperControls.add(hyperView);

    controls.add(zoomControls);
    controls.add(hyperControls);
    controls.add(modeControls);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:edu.ucla.stat.SOCR.analyses.gui.AnovaTwoWay.java

protected void setMappingPanel() {
    listIndex = new int[dataTable.getColumnCount()];
    for (int j = 0; j < listIndex.length; j++)
        listIndex[j] = 1;/*from ww w.  j  a v  a 2 s  . c  o m*/

    bPanel = new JPanel(new BorderLayout());
    bPanel.add(mappingPanel, BorderLayout.CENTER);
    mappingPanel.add(mappingInnerPanel, BorderLayout.CENTER);

    addButton1.addActionListener(this);
    addButton2.addActionListener(this);
    removeButton1.addActionListener(this);
    removeButton2.addActionListener(this);

    lModel1 = new DefaultListModel();
    lModel2 = new DefaultListModel();
    lModel3 = new DefaultListModel();

    int cellWidth = 10;

    listAdded = new JList(lModel1);
    listAdded.setSelectedIndex(0);
    listDepRemoved = new JList(lModel2);
    listIndepRemoved = new JList(lModel3);

    paintTable(listIndex);
    listAdded.setFixedCellWidth(cellWidth);
    listDepRemoved.setFixedCellWidth(cellWidth);
    listIndepRemoved.setFixedCellWidth(cellWidth);
    dependentPane = new JScrollPane(listDepRemoved);
    FIRST_BUTTON_LABEL = "DEPENDENT";
    SECOND_BUTTON_LABEL = "INDEPENDENT";
    depLabel = new JLabel(FIRST_BUTTON_LABEL);
    indLabel = new JLabel(SECOND_BUTTON_LABEL);
    tools1.add(depLabel);
    tools2.add(indLabel);

    tools1.add(addButton1);
    tools1.add(removeButton1);
    tools2.add(addButton2);
    tools2.add(removeButton2);

    tools1.setFloatable(false);
    tools2.setFloatable(false);

    //
    JPanel choicesPanel = new JPanel();
    choicesPanel.setLayout(new BoxLayout(choicesPanel, BoxLayout.Y_AXIS));
    interactionOnSwitch = new JRadioButton("On");
    interactionOnSwitch.addActionListener(this);
    interactionOnSwitch.setActionCommand(INTERACTIONON);
    interactionOnSwitch.setSelected(false);
    interactionOn = false;

    interactionOffSwitch = new JRadioButton("Off");
    interactionOffSwitch.addActionListener(this);
    interactionOffSwitch.setActionCommand(INTERACTIONOFF);
    interactionOffSwitch.setSelected(true);

    ButtonGroup group = new ButtonGroup();
    group.add(interactionOnSwitch);
    group.add(interactionOffSwitch);
    choicesPanel.add(new JLabel("Turn the interaction:"));
    choicesPanel.add(interactionOnSwitch);
    choicesPanel.add(interactionOffSwitch);
    choicesPanel.setPreferredSize(new Dimension(200, 100));

    JPanel emptyPanel = new JPanel();
    //mappingInnerPanel.setBackground(Color.RED);
    mappingInnerPanel.add(new JScrollPane(listAdded));
    mappingInnerPanel.add(tools1);
    mappingInnerPanel.add(dependentPane);
    // mappingInnerPanel.add(emptyPanel);
    mappingInnerPanel.add(choicesPanel);
    mappingInnerPanel.add(tools2);
    mappingInnerPanel.add(new JScrollPane(listIndepRemoved));
    //listIndepRemoved.setBackground(Color.GREEN);
}

From source file:com.prezerak.windmill.gui.AveragesPanel.java

private void initialize() {
    setLayout(new BorderLayout(0, 0));
    JPanel controlsPanel = new JPanel();
    controlsPanel.setBackground(UIManager.getColor("Button.background"));
    controlsPanel.setBorder(null);//from   w  ww . ja v  a 2 s .  c o  m
    add(controlsPanel, BorderLayout.SOUTH);
    controlsPanel.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
            ColumnSpec.decode("100px"), FormFactory.UNRELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,
            FormFactory.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("101px"), FormFactory.RELATED_GAP_COLSPEC,
            FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("69px"),
            FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("left:max(46dlu;default)"),
            FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(25dlu;default)"), },
            new RowSpec[] { FormFactory.NARROW_LINE_GAP_ROWSPEC, RowSpec.decode("23px"),
                    FormFactory.LINE_GAP_ROWSPEC, RowSpec.decode("25px"), }));

    JButton btnReport = new JButton("Wind Report");
    controlsPanel.add(btnReport, "2, 2, fill, fill");
    btnReport.addActionListener(this);
    btnReport.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnReport.setActionCommand("Report");

    btnAlarmReport = new JButton("Alarm Report");
    btnAlarmReport.setActionCommand("Alarm Report");
    btnAlarmReport.addActionListener(this);
    btnAlarmReport.setFont(new Font("Tahoma", Font.PLAIN, 11));

    controlsPanel.add(btnAlarmReport, "4, 2");
    rdbtnVelocity = new JRadioButton("velocity");
    controlsPanel.add(rdbtnVelocity, "10, 2, left, default");
    rdbtnVelocity.setFont(new Font("Tahoma", Font.PLAIN, 11));

    rdbtnVelocity.setSelected(true);
    rdbtnVelocity.addItemListener(this);

    rdbtnDirection = new JRadioButton("direction");
    controlsPanel.add(rdbtnDirection, "12, 2, left, default");
    rdbtnDirection.setFont(new Font("Tahoma", Font.PLAIN, 11));

    rdbtnDirection.setSelected(true);
    rdbtnDirection.addItemListener(this);

    JButton btnPrintGraph = new JButton("Print Graph");
    controlsPanel.add(btnPrintGraph, "2, 4, fill, top");
    btnPrintGraph.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnPrintGraph.setActionCommand("Print Graph");
    btnPrintGraph.addActionListener(this);

    JButton btnBackToReal = new JButton("Back to Real Time ");
    controlsPanel.add(btnBackToReal, "4, 4, fill, top");
    btnBackToReal.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnBackToReal.setActionCommand("Back to Real");
    btnBackToReal.addActionListener(this);

    rdbtnGust = new JRadioButton("Gust");
    rdbtnGust.setSelected(true);
    rdbtnGust.addItemListener(this);
    rdbtnGust.setFont(new Font("Tahoma", Font.PLAIN, 11));
    controlsPanel.add(rdbtnGust, "10, 4, left, default");

    rdbtnHigh = new JRadioButton("High");
    rdbtnHigh.setSelected(true);
    rdbtnHigh.addItemListener(this);
    rdbtnHigh.setFont(new Font("Tahoma", Font.PLAIN, 11));
    controlsPanel.add(rdbtnHigh, "12, 4, left, default");

    rdbtnHigher = new JRadioButton("Higher");
    rdbtnHigher.setSelected(true);
    rdbtnHigher.setFont(new Font("Tahoma", Font.PLAIN, 11));
    rdbtnHigher.addItemListener(this);
    controlsPanel.add(rdbtnHigher, "14, 4, left, default");
}

From source file:it.cnr.icar.eric.client.ui.swing.FindParamsPanel.java

private JPanel createSearchTypePanel() {
    //It just has two radio buttons that Selects from Business and Adhoc Query
    JPanel searchTypePanel = new JPanel();

    businessButton = new JRadioButton(resourceBundle.getString("button.businessQuery"));
    businessButton.setMnemonic(KeyEvent.VK_B);
    businessButton.setSelected(true);/*w  ww  .j  av  a 2  s .c o m*/
    businessButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            cardLayout.show(paramEntryParentPanel, "businessPanel");
            businessQuery = true;
        }
    });

    adhocButton = new JRadioButton(resourceBundle.getString("button.adHocQuery"));
    adhocButton.setMnemonic(KeyEvent.VK_A);
    adhocButton.setSelected(false);
    adhocButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            cardLayout.show(paramEntryParentPanel, "adhocPanel");
            businessQuery = false;
        }
    });

    ButtonGroup buttonGroup = new ButtonGroup();
    buttonGroup.add(businessButton);
    buttonGroup.add(adhocButton);

    searchTypePanel.add(businessButton);
    searchTypePanel.add(adhocButton);

    return searchTypePanel;
}

From source file:com.mirth.connect.connectors.file.AdvancedSftpSettingsDialog.java

private void initComponents() {
    authenticationLabel = new JLabel("Authentication:");

    usePasswordRadio = new JRadioButton("Password");
    usePasswordRadio.setFocusable(false);
    usePasswordRadio.setBackground(new Color(255, 255, 255));
    usePasswordRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    usePasswordRadio.setToolTipText("Select this option to use a password to gain access to the server.");
    usePasswordRadio.addActionListener(new ActionListener() {
        @Override/* w  w  w  .ja  v a2  s.c om*/
        public void actionPerformed(ActionEvent e) {
            authenticationRadioButtonActionPerformed();
        }
    });

    usePrivateKeyRadio = new JRadioButton("Public Key");
    usePrivateKeyRadio.setSelected(true);
    usePrivateKeyRadio.setFocusable(false);
    usePrivateKeyRadio.setBackground(UIConstants.BACKGROUND_COLOR);
    usePrivateKeyRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    usePrivateKeyRadio
            .setToolTipText("Select this option to use a public/private keypair to gain access to the server.");
    usePrivateKeyRadio.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            authenticationRadioButtonActionPerformed();
        }
    });

    useBothRadio = new JRadioButton("Both");
    useBothRadio.setSelected(true);
    useBothRadio.setFocusable(false);
    useBothRadio.setBackground(UIConstants.BACKGROUND_COLOR);
    useBothRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    useBothRadio.setToolTipText(
            "Select this option to use both a password and a public/private keypair to gain access to the server.");
    useBothRadio.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            authenticationRadioButtonActionPerformed();
        }
    });

    privateKeyButtonGroup = new ButtonGroup();
    privateKeyButtonGroup.add(usePasswordRadio);
    privateKeyButtonGroup.add(usePrivateKeyRadio);
    privateKeyButtonGroup.add(useBothRadio);

    keyLocationLabel = new JLabel("Public/Private Key File:");
    keyLocationField = new JTextField();
    keyLocationField.setToolTipText(
            "The absolute file path of the public/private keypair used to gain access to the remote server.");

    passphraseLabel = new JLabel("Passphrase:");
    passphraseField = new JPasswordField();
    passphraseField.setToolTipText("The passphrase associated with the public/private keypair.");

    useKnownHostsLabel = new JLabel("Host Key Checking:");

    useKnownHostsYesRadio = new JRadioButton("Yes");
    useKnownHostsYesRadio.setFocusable(false);
    useKnownHostsYesRadio.setBackground(UIConstants.BACKGROUND_COLOR);
    useKnownHostsYesRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    useKnownHostsYesRadio.setToolTipText(
            "<html>Select this option to validate the server's host key within the provided<br>Known Hosts file. Known Hosts file is required.</html>");

    useKnownHostsAskRadio = new JRadioButton("Ask");
    useKnownHostsAskRadio.setFocusable(false);
    useKnownHostsAskRadio.setBackground(UIConstants.BACKGROUND_COLOR);
    useKnownHostsAskRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    useKnownHostsAskRadio.setToolTipText(
            "<html>Select this option to ask the user to add the server's host key to the provided<br>Known Hosts file. Known Hosts file is optional.</html>");

    useKnownHostsNoRadio = new JRadioButton("No");
    useKnownHostsNoRadio.setSelected(true);
    useKnownHostsNoRadio.setFocusable(false);
    useKnownHostsNoRadio.setBackground(UIConstants.BACKGROUND_COLOR);
    useKnownHostsNoRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    useKnownHostsNoRadio.setToolTipText(
            "<html>Select this option to always add the server's host key to the provided<br>Known Hosts file. Known Hosts file is optional.</html>");

    knownHostsButtonGroup = new ButtonGroup();
    knownHostsButtonGroup.add(useKnownHostsYesRadio);
    knownHostsButtonGroup.add(useKnownHostsAskRadio);
    knownHostsButtonGroup.add(useKnownHostsNoRadio);

    knownHostsLocationLabel = new JLabel("Known Hosts File:");
    knownHostsField = new JTextField();
    knownHostsField
            .setToolTipText("The path to the local Known Hosts file used to authenticate the remote server.");

    configurationsLabel = new JLabel("Configuration Options:");
    configurationsTable = new MirthTable();

    Object[][] tableData = new Object[0][1];
    configurationsTable.setModel(new RefreshTableModel(tableData, new String[] { "Name", "Value" }));
    configurationsTable.setOpaque(true);
    configurationsTable.getColumnModel()
            .getColumn(configurationsTable.getColumnModel().getColumnIndex(NAME_COLUMN_NAME))
            .setCellEditor(new ConfigTableCellEditor(true));
    configurationsTable.getColumnModel()
            .getColumn(configurationsTable.getColumnModel().getColumnIndex(VALUE_COLUMN_NAME))
            .setCellEditor(new ConfigTableCellEditor(false));

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        Highlighter highlighter = HighlighterFactory.createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR,
                UIConstants.BACKGROUND_COLOR);
        configurationsTable.setHighlighters(highlighter);
    }

    configurationsScrollPane = new JScrollPane();
    configurationsScrollPane.getViewport().add(configurationsTable);

    newButton = new JButton("New");
    newButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultTableModel model = (DefaultTableModel) configurationsTable.getModel();

            Vector<String> row = new Vector<String>();
            String header = "Property";

            for (int i = 1; i <= configurationsTable.getRowCount() + 1; i++) {
                boolean exists = false;
                for (int index = 0; index < configurationsTable.getRowCount(); index++) {
                    if (((String) configurationsTable.getValueAt(index, 0)).equalsIgnoreCase(header + i)) {
                        exists = true;
                    }
                }

                if (!exists) {
                    row.add(header + i);
                    break;
                }
            }

            model.addRow(row);

            int rowSelectionNumber = configurationsTable.getRowCount() - 1;
            configurationsTable.setRowSelectionInterval(rowSelectionNumber, rowSelectionNumber);

            Boolean enabled = deleteButton.isEnabled();
            if (!enabled) {
                deleteButton.setEnabled(true);
            }
        }
    });

    deleteButton = new JButton("Delete");
    deleteButton.setEnabled(false);
    deleteButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int rowSelectionNumber = configurationsTable.getSelectedRow();
            if (rowSelectionNumber > -1) {
                DefaultTableModel model = (DefaultTableModel) configurationsTable.getModel();
                model.removeRow(rowSelectionNumber);

                rowSelectionNumber--;
                if (rowSelectionNumber > -1) {
                    configurationsTable.setRowSelectionInterval(rowSelectionNumber, rowSelectionNumber);
                }

                if (configurationsTable.getRowCount() == 0) {
                    deleteButton.setEnabled(false);
                }
            }
        }
    });

    okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            okCancelButtonActionPerformed();
        }
    });

    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            dispose();
        }
    });

    authenticationRadioButtonActionPerformed();
}

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

public PreferencesDialog(final DownloaderGUI owner, Properties config) {
    super(owner, "Preferences", true);

    HttpClientParams params = new HttpClientParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    params.setSoTimeout(30000);/*from   w  w  w .  j av  a  2s  . com*/
    client = new HttpClient(params);
    setProxy(ProxyCfg.parseConfig(config));

    sample = new Deviation();
    sample.setId(15972367L);
    sample.setTitle("Fella Promo");
    sample.setArtist("devart");
    sample.setImageDownloadUrl(DOWNLOAD_URL);
    sample.setImageFilename(Deviation.extractFilename(DOWNLOAD_URL));
    sample.setCollection(new Collection(1L, "MyCollect"));
    setLayout(new BorderLayout());
    panes = new JTabbedPane(JTabbedPane.TOP);

    JPanel genPanel = new JPanel();
    BoxLayout genLayout = new BoxLayout(genPanel, BoxLayout.Y_AXIS);
    genPanel.setLayout(genLayout);
    panes.add("General", genPanel);

    JLabel userLabel = new JLabel("Username");

    userLabel.setToolTipText("The username the account you want to download the favorites from.");

    userField = new JTextField(config.getProperty(Constants.USERNAME));

    userLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    userField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userField.setMaximumSize(new Dimension(Integer.MAX_VALUE, userField.getFont().getSize() * 2));

    genPanel.add(userLabel);
    genPanel.add(userField);

    JPanel radioPanel = new JPanel();
    BoxLayout radioLayout = new BoxLayout(radioPanel, BoxLayout.X_AXIS);
    radioPanel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    radioPanel.setBorder(new EmptyBorder(0, 5, 0, 5));

    radioPanel.setLayout(radioLayout);

    JLabel searchLabel = new JLabel("Search for");
    searchLabel
            .setToolTipText("Select what you want to download from that user: it favorites or it galleries.");
    searchLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searchLabel.setBorder(new EmptyBorder(0, 5, 0, 5));

    selectedSearch = SEARCH.lookup(config.getProperty(Constants.SEARCH, SEARCH.getDefault().getId()));
    buttonGroup = new ButtonGroup();

    for (final SEARCH search : SEARCH.values()) {
        JRadioButton radio = new JRadioButton(search.getLabel());
        radio.setAlignmentX(JLabel.LEFT_ALIGNMENT);
        radio.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                selectedSearch = search;
            }
        });

        buttonGroup.add(radio);
        radioPanel.add(radio);
        if (search.equals(selectedSearch)) {
            radio.setSelected(true);
        }
    }

    genPanel.add(radioPanel);

    final JTextField sampleField = new JTextField("");
    sampleField.setEditable(false);

    JLabel locationLabel = new JLabel("Download location");
    locationLabel.setToolTipText("The folder pattern where you want the file to be downloaded in.");

    JLabel legendsLabel = new JLabel(
            "<html><body>Field names: %user%, %artist%, %title%, %id%, %filename%, %collection%, %ext%<br></br>Example:</body></html>");
    legendsLabel.setToolTipText("An example of where a file will be downloaded to.");

    locationString = new StringBuilder();
    locationField = new JTextField(config.getProperty(Constants.LOCATION));
    locationField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationString.setLength(0);
            locationString.append(dest.getAbsolutePath());
            sampleField.setText(locationString.toString());
            if (useSameForMatureBox.isSelected()) {
                locationMatureString.setLength(0);
                locationMatureString.append(sampleField.getText());
                locationMatureField.setText(locationField.getText());
            }
        }

        public void keyTyped(KeyEvent e) {
        }

    });
    locationField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });
    JLabel locationMatureLabel = new JLabel("Mature download location");
    locationMatureLabel.setToolTipText(
            "The folder pattern where you want the file marked as 'Mature' to be downloaded in.");

    locationMatureString = new StringBuilder();
    locationMatureField = new JTextField(config.getProperty(Constants.MATURE));
    locationMatureField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationMatureString.setLength(0);
            locationMatureString.append(dest.getAbsolutePath());
            sampleField.setText(locationMatureString.toString());
        }

        public void keyTyped(KeyEvent e) {
        }

    });

    locationMatureField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationMatureString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });

    useSameForMatureBox = new JCheckBox("Use same location for mature deviation?");
    useSameForMatureBox.setSelected(locationLabel.getText().equals(locationMatureField.getText()));
    useSameForMatureBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (useSameForMatureBox.isSelected()) {
                locationMatureField.setEditable(false);
                locationMatureField.setText(locationField.getText());
                locationMatureString.setLength(0);
                locationMatureString.append(locationString);
            } else {
                locationMatureField.setEditable(true);
            }

        }
    });

    File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    sampleField.setText(dest.getAbsolutePath());
    locationString.append(sampleField.getText());

    dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    locationMatureString.append(dest.getAbsolutePath());

    locationLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationField.setMaximumSize(new Dimension(Integer.MAX_VALUE, locationField.getFont().getSize() * 2));
    locationMatureLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationMatureField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureField
            .setMaximumSize(new Dimension(Integer.MAX_VALUE, locationMatureField.getFont().getSize() * 2));
    useSameForMatureBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    legendsLabel.setMaximumSize(new Dimension(Integer.MAX_VALUE, legendsLabel.getFont().getSize() * 2));
    sampleField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    sampleField.setMaximumSize(new Dimension(Integer.MAX_VALUE, sampleField.getFont().getSize() * 2));

    genPanel.add(locationLabel);
    genPanel.add(locationField);

    genPanel.add(locationMatureLabel);
    genPanel.add(locationMatureField);
    genPanel.add(useSameForMatureBox);

    genPanel.add(legendsLabel);
    genPanel.add(sampleField);
    genPanel.add(Box.createVerticalBox());

    final KeyListener prxChangeListener = new KeyListener() {

        public void keyTyped(KeyEvent e) {
            proxyChangeState = true;
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
        }
    };

    JPanel prxPanel = new JPanel();
    BoxLayout prxLayout = new BoxLayout(prxPanel, BoxLayout.Y_AXIS);
    prxPanel.setLayout(prxLayout);
    panes.add("Proxy", prxPanel);

    JLabel prxHostLabel = new JLabel("Proxy Host");
    prxHostLabel.setToolTipText("The hostname of the proxy server");
    prxHostField = new JTextField(config.getProperty(Constants.PROXY_HOST));
    prxHostLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxHostField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxHostField.getFont().getSize() * 2));

    JLabel prxPortLabel = new JLabel("Proxy Port");
    prxPortLabel.setToolTipText("The port of the proxy server (Default 80).");

    prxPortSpinner = new JSpinner();
    prxPortSpinner.setModel(new SpinnerNumberModel(
            Integer.parseInt(config.getProperty(Constants.PROXY_PORT, "80")), 1, 65535, 1));

    prxPortLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPortSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPortSpinner.getFont().getSize() * 2));

    JLabel prxUserLabel = new JLabel("Proxy username");
    prxUserLabel.setToolTipText("The username used for authentication, if applicable.");
    prxUserField = new JTextField(config.getProperty(Constants.PROXY_USERNAME));
    prxUserLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxUserField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxUserField.getFont().getSize() * 2));

    JLabel prxPassLabel = new JLabel("Proxy username");
    prxPassLabel.setToolTipText("The username used for authentication, if applicable.");
    prxPassField = new JPasswordField(config.getProperty(Constants.PROXY_PASSWORD));
    prxPassLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPassField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPassField.getFont().getSize() * 2));

    prxUseBox = new JCheckBox("Use a proxy?");
    prxUseBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            prxChangeListener.keyTyped(null);

            if (prxUseBox.isSelected()) {
                prxHostField.setEditable(true);
                prxPortSpinner.setEnabled(true);
                prxUserField.setEditable(true);
                prxPassField.setEditable(true);

            } else {
                prxHostField.setEditable(false);
                prxPortSpinner.setEnabled(false);
                prxUserField.setEditable(false);
                prxPassField.setEditable(false);
            }
        }
    });

    prxUseBox.setSelected(!Boolean.parseBoolean(config.getProperty(Constants.PROXY_USE)));
    prxUseBox.doClick();
    proxyChangeState = false;

    prxHostField.addKeyListener(prxChangeListener);
    prxUserField.addKeyListener(prxChangeListener);
    prxPassField.addKeyListener(prxChangeListener);
    prxPortSpinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            proxyChangeState = true;
        }
    });
    prxPanel.add(prxUseBox);

    prxPanel.add(prxHostLabel);
    prxPanel.add(prxHostField);

    prxPanel.add(prxPortLabel);
    prxPanel.add(prxPortSpinner);

    prxPanel.add(prxUserLabel);
    prxPanel.add(prxUserField);

    prxPanel.add(prxPassLabel);
    prxPanel.add(prxPassField);
    prxPanel.add(Box.createVerticalBox());

    final JPanel advPanel = new JPanel();
    BoxLayout advLayout = new BoxLayout(advPanel, BoxLayout.Y_AXIS);
    advPanel.setLayout(advLayout);
    panes.add("Advanced", advPanel);
    panes.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            JTabbedPane pane = (JTabbedPane) e.getSource();

            if (proxyChangeState && pane.getSelectedComponent() == advPanel) {
                Properties properties = new Properties();
                properties.setProperty(Constants.PROXY_USERNAME, prxUserField.getText().trim());
                properties.setProperty(Constants.PROXY_PASSWORD, new String(prxPassField.getPassword()).trim());
                properties.setProperty(Constants.PROXY_HOST, prxHostField.getText().trim());
                properties.setProperty(Constants.PROXY_PORT, prxPortSpinner.getValue().toString());
                properties.setProperty(Constants.PROXY_USE, Boolean.toString(prxUseBox.isSelected()));
                ProxyCfg prx = ProxyCfg.parseConfig(properties);
                setProxy(prx);
                revalidateSearcher(null);
            }
        }
    });
    JLabel domainLabel = new JLabel("Deviant Art domain name");
    domainLabel.setToolTipText("The deviantART main domain, should it ever change.");

    domainField = new JTextField(config.getProperty(Constants.DOMAIN));
    domainLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    domainField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainField.setMaximumSize(new Dimension(Integer.MAX_VALUE, domainField.getFont().getSize() * 2));

    advPanel.add(domainLabel);
    advPanel.add(domainField);

    JLabel throttleLabel = new JLabel("Throttle search delay");
    throttleLabel.setToolTipText(
            "Slow down search query by inserting a pause between them. This help prevent abuse when doing a massive download.");

    throttleSpinner = new JSpinner();
    throttleSpinner.setModel(
            new SpinnerNumberModel(Integer.parseInt(config.getProperty(Constants.THROTTLE, "0")), 5, 60, 1));

    throttleLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    throttleSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, throttleSpinner.getFont().getSize() * 2));

    advPanel.add(throttleLabel);
    advPanel.add(throttleSpinner);

    JLabel searcherLabel = new JLabel("Searcher");
    searcherLabel.setToolTipText("Select a searcher that will look for your favorites.");

    searcherBox = new JComboBox();
    searcherBox.setRenderer(new TogglingRenderer());

    final AtomicInteger index = new AtomicInteger(0);
    searcherBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox) e.getSource();
            Object selectedItem = combo.getSelectedItem();
            if (selectedItem instanceof SearchItem) {
                SearchItem item = (SearchItem) selectedItem;
                if (item.isValid) {
                    index.set(combo.getSelectedIndex());
                } else {
                    combo.setSelectedIndex(index.get());
                }
            }
        }
    });

    try {
        for (Class<Search> clazz : SearcherClassCache.getInstance().getClasses()) {

            Search searcher = clazz.newInstance();
            String name = searcher.getName();

            SearchItem item = new SearchItem(name, clazz.getName(), true);
            searcherBox.addItem(item);
        }
        String selectedClazz = config.getProperty(Constants.SEARCHER,
                com.dragoniade.deviantart.deviation.SearchRss.class.getName());
        revalidateSearcher(selectedClazz);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    searcherLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    searcherBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, searcherBox.getFont().getSize() * 2));

    advPanel.add(searcherLabel);
    advPanel.add(searcherBox);

    advPanel.add(Box.createVerticalBox());

    add(panes, BorderLayout.CENTER);

    JButton saveBut = new JButton("Save");

    userField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            if (field.getText().trim().length() == 0) {
                JOptionPane.showMessageDialog(input, "The user musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The location must contains at least a %filename% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationMatureField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The Mature location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The Mature location must contains at least a %username% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    domainField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String domain = field.getText().trim();
            if (domain.length() == 0) {
                JOptionPane.showMessageDialog(input, "You must specify the deviantART main domain.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (domain.toLowerCase().startsWith("http://")) {
                JOptionPane.showMessageDialog(input,
                        "You must specify the deviantART main domain, not the full URL (aka www.deviantart.com).",
                        "Warning", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            return true;
        }
    });
    locationField.setVerifyInputWhenFocusTarget(true);

    final JDialog parent = this;
    saveBut.addActionListener(new ActionListener() {

        String errorMsg = "The location is invalid or cannot be written to.";

        public void actionPerformed(ActionEvent e) {

            String username = userField.getText().trim();
            String location = locationField.getText().trim();
            String locationMature = locationMatureField.getText().trim();
            String domain = domainField.getText().trim();
            String throttle = throttleSpinner.getValue().toString();
            String searcher = searcherBox.getSelectedItem().toString();

            String prxUse = Boolean.toString(prxUseBox.isSelected());
            String prxHost = prxHostField.getText().trim();
            String prxPort = prxPortSpinner.getValue().toString();
            String prxUsername = prxUserField.getText().trim();
            String prxPassword = new String(prxPassField.getPassword()).trim();

            if (!testPath(location, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (!testPath(locationMature, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }

            Properties p = new Properties();
            p.setProperty(Constants.USERNAME, username);
            p.setProperty(Constants.LOCATION, location);
            p.setProperty(Constants.MATURE, locationMature);
            p.setProperty(Constants.DOMAIN, domain);
            p.setProperty(Constants.THROTTLE, throttle);
            p.setProperty(Constants.SEARCHER, searcher);
            p.setProperty(Constants.SEARCH, selectedSearch.getId());

            p.setProperty(Constants.PROXY_USE, prxUse);
            p.setProperty(Constants.PROXY_HOST, prxHost);
            p.setProperty(Constants.PROXY_PORT, prxPort);
            p.setProperty(Constants.PROXY_USERNAME, prxUsername);
            p.setProperty(Constants.PROXY_PASSWORD, prxPassword);

            owner.savePreferences(p);
            parent.dispose();
        }
    });

    JButton cancelBut = new JButton("Cancel");
    cancelBut.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            parent.dispose();
        }
    });

    JPanel buttonPanel = new JPanel();
    BoxLayout butLayout = new BoxLayout(buttonPanel, BoxLayout.X_AXIS);
    buttonPanel.setLayout(butLayout);

    buttonPanel.add(saveBut);
    buttonPanel.add(cancelBut);
    add(buttonPanel, BorderLayout.SOUTH);

    pack();
    setResizable(false);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);
    setVisible(true);
}

From source file:de.tbuchloh.kiskis.gui.dialogs.SecuredElementCreationDlg.java

private JPanel createButtonGroup() {
    final JPanel main = new JPanel(new GridLayout(TYPES.length, 1, 5, 5));
    main.setBorder(BorderFactory.createEmptyBorder(15, 50, 5, 150));
    _bg = new ButtonGroup();
    _buttons = new JRadioButton[TYPES.length];
    final String lastSelected = P.get(K_LAST_CREATED_SECURED_ELEMENT, NetAccount.class.getName());
    LOG.debug("Last created class: " + lastSelected);
    for (int i = 0; i < TYPES.length; ++i) {
        _buttons[i] = new JRadioButton(TYPES[i]._label);
        final Class c = TYPES[i]._clazz;
        if (c.getName().equals(lastSelected)) {
            _buttons[i].setSelected(true);
        }/*from  w ww .  j av  a  2  s . c  o  m*/
        _bg.add(_buttons[i]);
        Component comp = _buttons[i];
        if (c == GenericAccount.class) {
            final JPanel p = new JPanel(new BorderLayout(10, 0));
            p.add(comp);
            p.add(_templates, BorderLayout.EAST);
            _templates.addItemListener(new RadioItemListener(_buttons[i]));
            comp.setEnabled(_templates.isEnabled());
            comp = p;
        }
        main.add(comp);
    }
    return main;
}

From source file:net.sf.taverna.t2.activities.wsdlsir.views.WSDLActivityConfigurationView.java

private void initComponents() {

    this.setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);

    int gridy = 0;

    // title panel
    JPanel titlePanel = new JPanel(new BorderLayout());
    titlePanel.setBackground(Color.WHITE);
    JLabel titleLabel = new JLabel("Security configuration");
    titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 13.5f));
    titleLabel.setBorder(new EmptyBorder(10, 10, 0, 10));
    DialogTextArea titleMessage = new DialogTextArea("Select a security profile for the service");
    titleMessage.setMargin(new Insets(5, 20, 10, 10));
    titleMessage.setFont(titleMessage.getFont().deriveFont(11f));
    titleMessage.setEditable(false);/*ww w. j  av a  2s .  c om*/
    titleMessage.setFocusable(false);
    titlePanel.setBorder(new EmptyBorder(10, 10, 0, 10));
    titlePanel.add(titleLabel, BorderLayout.NORTH);
    titlePanel.add(titleMessage, BorderLayout.CENTER);
    addDivider(titlePanel, SwingConstants.BOTTOM, true);

    // Main panel
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridBagLayout());
    mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

    //Create the radio buttons
    noSecurityRadioButton = new JRadioButton("None");
    noSecurityRadioButton.addItemListener(this);

    wsSecurityAuthNRadioButton = new JRadioButton("WS-Security username and password authentication");
    wsSecurityAuthNRadioButton.addItemListener(this);

    httpSecurityAuthNRadioButton = new JRadioButton("HTTP username and password authentication");
    httpSecurityAuthNRadioButton.addItemListener(this);

    SAMLSecurityAuthNRadioButton = new JRadioButton("SAML WEB SSO profile authentication");
    SAMLSecurityAuthNRadioButton.addItemListener(this);

    //Group the radio buttons
    buttonGroup = new ButtonGroup();
    buttonGroup.add(noSecurityRadioButton);
    buttonGroup.add(wsSecurityAuthNRadioButton);
    buttonGroup.add(httpSecurityAuthNRadioButton);
    buttonGroup.add(SAMLSecurityAuthNRadioButton);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.weighty = 0.0;

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(noSecurityRadioButton, gbc);

    noSecurityLabel = new JLabel("Service requires no security");
    noSecurityLabel.setFont(noSecurityLabel.getFont().deriveFont(11f));
    //      addDivider(noSecurityLabel, SwingConstants.BOTTOM, false);
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(0, 40, 10, 10);
    mainPanel.add(noSecurityLabel, gbc);

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(httpSecurityAuthNRadioButton, gbc);

    ActionListener usernamePasswordListener = new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            // Get Credential Manager UI to get the username and password for the service
            CredentialManagerUI credManagerUI = CredentialManagerUI.getInstance();
            if (credManagerUI != null)
                credManagerUI.newPasswordForService(oldBean.getWsdl());
        }
    };

    httpSecurityAuthNLabel = new JLabel(
            "Service requires HTTP username and password in order to authenticate the user");
    httpSecurityAuthNLabel.setFont(httpSecurityAuthNLabel.getFont().deriveFont(11f));
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(0, 40, 10, 10);
    mainPanel.add(httpSecurityAuthNLabel, gbc);

    // Set username and password button;
    setHttpUsernamePasswordButton = new JButton("Set username and password");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.insets = new Insets(0, 40, 10, 10);
    gbc.weightx = 1.0;
    gbc.weighty = 1.0; // add any vertical space to this component
    mainPanel.add(setHttpUsernamePasswordButton, gbc);
    setHttpUsernamePasswordButton.addActionListener(usernamePasswordListener);

    /////SAML

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(SAMLSecurityAuthNRadioButton, gbc);

    ActionListener getCookieListener = new ActionListener() {

        /**
         * This listener will use the CallPreparator to obtain the cookies (included shibsession_XXX cookie) and 
         * save it in the Credential Manager (as the password for user "nomatter")
         */
        public void actionPerformed(ActionEvent e) {
            try {
                WSDLParser parser = new WSDLParser(newBean.getWsdl());
                List<String> endpoints = parser.getOperationEndpointLocations(newBean.getOperation());
                for (String endpoint : endpoints) //Actually i am only expecting one endpoint
                {
                    if (debug)
                        System.out
                                .println("Obtaining a SAML cookies to save in credential manager:" + endpoint);

                    Cookie[] cookies = CallPreparator.createCookieForCallToEndpoint(endpoint);

                    // Uncomment for just the shibsession cookie
                    //                  Cookie[] cookiessession = new Cookie[1];
                    //                  for (Cookie cook : cookies)
                    //                     if (cook.getName().contains("shibsession"))
                    //                        cookiessession[0]=cook;
                    //                  cookies=cookiessession;

                    CredentialManager credman = CredentialManager.getInstance();
                    credman.saveUsernameAndPasswordForService(
                            new UsernamePassword("nomatter", serializetoString(cookies)), new URI(endpoint));
                }
            } catch (WSDLException ex) {
                System.err.println(
                        "Problem getting or saving SAML cookie: " + newBean.getWsdl() + ". " + ex.getMessage());
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                System.err.println(
                        "Problem getting or saving SAML cookie: " + newBean.getWsdl() + ". " + ex.getMessage());
                ex.printStackTrace();
            } catch (Exception ex) {
                System.err.println(
                        "Problem getting or saving SAML cookie: " + newBean.getWsdl() + ". " + ex.getMessage());
                ex.printStackTrace();
            }
        }
    };

    SAMLSecurityAuthNLabel = new JLabel("<html>"
            + "Service requires SAML Web SSO profile to be perfomed in order to authenticate the user. "
            + "A cookie will be saved in your Credential Manger. "
            + "In the case that it stops working, please delete the entry in your Credential Manager or re-authenticate"
            + "</html>");
    SAMLSecurityAuthNLabel.setFont(SAMLSecurityAuthNLabel.getFont().deriveFont(11f));
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(3, 40, 10, 10);
    mainPanel.add(SAMLSecurityAuthNLabel, gbc);

    // Set username and password button;
    setSAMLGETCookieButton = new JButton("Authenticate and save Authentication data in Credential Manger");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.insets = new Insets(0, 40, 10, 10);
    gbc.weightx = 1.0;
    gbc.weighty = 1.0; // add any vertical space to this component
    mainPanel.add(setSAMLGETCookieButton, gbc);
    setSAMLGETCookieButton.addActionListener(getCookieListener);

    //END SAML

    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 10, 0, 0);
    mainPanel.add(wsSecurityAuthNRadioButton, gbc);

    wsSecurityAuthNLabel = new JLabel(
            "Service requires WS-Security username and password in order to authenticate the user");
    wsSecurityAuthNLabel.setFont(wsSecurityAuthNLabel.getFont().deriveFont(11f));
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(0, 40, 0, 0);
    mainPanel.add(wsSecurityAuthNLabel, gbc);

    // Password type list
    passwordTypeComboBox = new JComboBox(passwordTypes);
    passwordTypeComboBox.setRenderer(new ComboBoxTooltipRenderer());
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(10, 40, 0, 0);
    mainPanel.add(passwordTypeComboBox, gbc);

    // 'Add timestamp' checkbox
    addTimestampCheckBox = new JCheckBox("Add a timestamp to SOAP message");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.insets = new Insets(5, 40, 10, 10);
    mainPanel.add(addTimestampCheckBox, gbc);

    // Set username and password button;
    setWsdlUsernamePasswordButton = new JButton("Set username and password");
    gbc.gridx = 0;
    gbc.gridy = gridy++;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.EAST;
    gbc.insets = new Insets(0, 40, 10, 10);
    gbc.weightx = 1.0;
    gbc.weighty = 1.0; // add any vertical space to this component
    mainPanel.add(setWsdlUsernamePasswordButton, gbc);
    setWsdlUsernamePasswordButton.addActionListener(usernamePasswordListener);

    addDivider(mainPanel, SwingConstants.BOTTOM, true);

    // OK/Cancel button panel
    JPanel okCancelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    JButton okButton = new JButton("OK");
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            okPressed();
        }
    });
    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            cancelPressed();
        }
    });
    okCancelPanel.add(cancelButton);
    okCancelPanel.add(okButton);

    // Enable/disable controls based on what is the current security profiles
    String securityProfile = oldBean.getSecurityProfile();
    if (securityProfile == null) {
        noSecurityRadioButton.setSelected(true);
    } else {
        if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)) {
            wsSecurityAuthNRadioButton.setSelected(true);
        }
        if (securityProfile.equals(SecurityProfiles.HTTP_BASIC_AUTHN)
                || securityProfile.equals(SecurityProfiles.HTTP_DIGEST_AUTHN)) {
            httpSecurityAuthNRadioButton.setSelected(true);
        }
        if (securityProfile.equals(SecurityProfiles.SAMLWEBSSOAUTH)) {
            SAMLSecurityAuthNRadioButton.setSelected(true);
        }
        if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD)
                || securityProfile
                        .equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)) {
            passwordTypeComboBox.setSelectedItem(PLAINTEXT_PASSWORD);
        } else if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD)
                || securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)) {
            passwordTypeComboBox.setSelectedItem(DIGEST_PASSWORD);
        }
        if (securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)
                || securityProfile
                        .equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)) {
            addTimestampCheckBox.setSelected(true);
        } else {
            addTimestampCheckBox.setSelected(false);
        }
    }

    // Put everything together
    JPanel layoutPanel = new JPanel(new BorderLayout());
    layoutPanel.add(titlePanel, BorderLayout.NORTH);
    layoutPanel.add(mainPanel, BorderLayout.CENTER);
    layoutPanel.add(okCancelPanel, BorderLayout.SOUTH);
    layoutPanel.setPreferredSize(new Dimension(550, 490));

    this.getContentPane().add(layoutPanel);
    this.pack();
}