Example usage for javax.swing JTextField setText

List of usage examples for javax.swing JTextField setText

Introduction

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

Prototype

@BeanProperty(bound = false, description = "the text of this component")
public void setText(String t) 

Source Link

Document

Sets the text of this TextComponent to the specified text.

Usage

From source file:userinterface.properties.GUIGraphHandler.java

public void plotNewFunction() {

    JDialog dialog;/*from   w  w  w. ja va  2 s .co  m*/
    JRadioButton radio2d, radio3d, newGraph, existingGraph;
    JTextField functionField, seriesName;
    JButton ok, cancel;
    JComboBox<String> chartOptions;
    JLabel example;

    //init all the fields of the dialog
    dialog = new JDialog(GUIPrism.getGUI());
    radio2d = new JRadioButton("2D");
    radio3d = new JRadioButton("3D");
    newGraph = new JRadioButton("New Graph");
    existingGraph = new JRadioButton("Exisiting");
    chartOptions = new JComboBox<String>();
    functionField = new JTextField();
    ok = new JButton("Plot");
    cancel = new JButton("Cancel");
    seriesName = new JTextField();
    example = new JLabel("<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
    example.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.HAND_CURSOR));
            example.setForeground(Color.BLUE);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            example.setForeground(Color.BLACK);
        }

        @Override
        public void mouseClicked(MouseEvent e) {

            if (e.getButton() == MouseEvent.BUTTON1) {

                if (radio2d.isSelected()) {
                    functionField.setText("x/2 + 5");
                } else {
                    functionField.setText("x+y+5");
                }

                functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
                functionField.setForeground(Color.BLACK);

            }
        }

    });

    //set dialog properties
    dialog.setSize(400, 350);
    dialog.setTitle("Plot a new function");
    dialog.setModal(true);
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setLocationRelativeTo(GUIPrism.getGUI());

    //add every component to their dedicated panels
    JPanel graphTypePanel = new JPanel(new FlowLayout());
    graphTypePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function type"));
    graphTypePanel.add(radio2d);
    graphTypePanel.add(radio3d);

    JPanel functionFieldPanel = new JPanel(new BorderLayout());
    functionFieldPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function"));
    functionFieldPanel.add(functionField, BorderLayout.CENTER);
    functionFieldPanel.add(example, BorderLayout.SOUTH);

    JPanel chartSelectPanel = new JPanel();
    chartSelectPanel.setLayout(new BoxLayout(chartSelectPanel, BoxLayout.Y_AXIS));
    chartSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Plot function to"));
    JPanel radioPlotPanel = new JPanel(new FlowLayout());
    radioPlotPanel.add(newGraph);
    radioPlotPanel.add(existingGraph);
    JPanel chartOptionsPanel = new JPanel(new FlowLayout());
    chartOptionsPanel.add(chartOptions);
    chartSelectPanel.add(radioPlotPanel);
    chartSelectPanel.add(chartOptionsPanel);

    JPanel bottomControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomControlPanel.add(ok);
    bottomControlPanel.add(cancel);

    JPanel seriesNamePanel = new JPanel(new BorderLayout());
    seriesNamePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Series name"));
    seriesNamePanel.add(seriesName, BorderLayout.CENTER);

    // add all the panels to the dialog

    dialog.add(graphTypePanel);
    dialog.add(functionFieldPanel);
    dialog.add(chartSelectPanel);
    dialog.add(seriesNamePanel);
    dialog.add(bottomControlPanel);

    // do all the enables and set properties

    radio2d.setSelected(true);
    newGraph.setSelected(true);
    chartOptions.setEnabled(false);
    functionField.setText("Add function expression here....");
    functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
    functionField.setForeground(Color.GRAY);
    seriesName.setText("New function");
    ok.setMnemonic('P');
    cancel.setMnemonic('C');
    example.setToolTipText("click to try out");

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

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

    boolean found = false;

    for (int i = 0; i < theTabs.getTabCount(); i++) {

        if (theTabs.getComponentAt(i) instanceof Graph) {
            chartOptions.addItem(getGraphName(i));
            found = true;
        }
    }

    if (!found) {

        existingGraph.setEnabled(false);
        chartOptions.setEnabled(false);
    }

    //add all the action listeners

    radio2d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio2d.isSelected()) {

                radio3d.setSelected(false);

                if (chartOptions.getItemCount() > 0) {
                    existingGraph.setEnabled(true);
                    chartOptions.setEnabled(true);
                }

                example.setText(
                        "<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
            }
        }
    });

    radio3d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio3d.isSelected()) {

                radio2d.setSelected(false);
                newGraph.setSelected(true);
                existingGraph.setEnabled(false);
                chartOptions.setEnabled(false);
                example.setText("<html><font size=3 color=red>Example:</font><font size=3>x+y+5</font></html>");

            }

        }
    });

    newGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (newGraph.isSelected()) {
                existingGraph.setSelected(false);
                chartOptions.setEnabled(false);
            }
        }
    });

    existingGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existingGraph.isSelected()) {

                newGraph.setSelected(false);
                chartOptions.setEnabled(true);
            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String function = functionField.getText();

            Expression expr = null;

            try {

                expr = GUIPrism.getGUI().getPrism().parseSingleExpressionString(function);
                expr = (Expression) expr.accept(new ASTTraverseModify() {

                    @Override
                    public Object visit(ExpressionIdent e) throws PrismLangException {
                        return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                    }

                });

                expr.typeCheck();
                expr.semanticCheck();

            } catch (PrismLangException e1) {

                // for copying style
                JLabel label = new JLabel();

                // html content in our case the error we want to show
                JEditorPane ep = new JEditorPane("text/html",
                        "<html> There was an error parsing the function. To read about what built-in"
                                + " functions are supported <br>and some more information on the functions, visit "
                                + "<a href='http://www.prismmodelchecker.org/manual/ThePRISMLanguage/Expressions'>Prism expressions site</a>."
                                + "<br><br><font color=red>Error: </font>" + e1.getMessage() + " </html>");

                // handle link events
                ep.addHyperlinkListener(new HyperlinkListener() {
                    @Override
                    public void hyperlinkUpdate(HyperlinkEvent e) {
                        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                            try {
                                Desktop.getDesktop().browse(e.getURL().toURI());
                            } catch (IOException | URISyntaxException e1) {

                                e1.printStackTrace();
                            }
                        }
                    }
                });
                ep.setEditable(false);
                ep.setBackground(label.getBackground());

                // show the error dialog
                JOptionPane.showMessageDialog(dialog, ep, "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (radio2d.isSelected()) {

                ParametricGraph graph = null;

                if (newGraph.isSelected()) {

                    graph = new ParametricGraph("");
                } else {

                    for (int i = 0; i < theTabs.getComponentCount(); i++) {

                        if (theTabs.getTitleAt(i).equals(chartOptions.getSelectedItem())) {

                            graph = (ParametricGraph) theTabs.getComponent(i);
                        }
                    }

                }

                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), newGraph.isSelected(), true);

            } else if (radio3d.isSelected()) {

                try {

                    expr = (Expression) expr.accept(new ASTTraverseModify() {
                        @Override
                        public Object visit(ExpressionIdent e) throws PrismLangException {
                            return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                        }

                    });

                    expr.semanticCheck();
                    expr.typeCheck();

                } catch (PrismLangException e1) {
                    e1.printStackTrace();
                }

                if (expr.getAllConstants().size() < 2) {

                    JOptionPane.showMessageDialog(dialog,
                            "There are not enough variables in the function to plot a 3D chart!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // its always a new graph
                ParametricGraph3D graph = new ParametricGraph3D(expr);
                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), true, false);
            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    // we will show info about the function when field is out of focus
    functionField.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {

            if (!functionField.getText().equals("")) {
                return;
            }

            functionField.setText("Add function expression here....");
            functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
            functionField.setForeground(Color.GRAY);
        }

        @Override
        public void focusGained(FocusEvent e) {

            if (!functionField.getText().equals("Add function expression here....")) {
                return;
            }

            functionField.setForeground(Color.BLACK);
            functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
            functionField.setText("");
        }
    });

    // show the dialog
    dialog.setVisible(true);
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private JComponent initializeJComponentForParameter(final String strValue, final ParameterInfo info)
        throws ModelInformationException {
    JComponent field = null;/*from w  ww . j a v a2  s.c om*/

    if (info.isBoolean()) {
        field = new JCheckBox();
        boolean value = Boolean.parseBoolean(strValue);
        ((JCheckBox) field).setSelected(value);
    } else if (info.isEnum() || info instanceof MasonChooserParameterInfo) {
        Object[] elements = null;
        if (info.isEnum()) {
            final Class<Enum<?>> type = (Class<Enum<?>>) info.getJavaType();
            elements = type.getEnumConstants();
        } else {
            final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) info;
            elements = chooserInfo.getValidStrings();
        }
        final JComboBox list = new JComboBox(elements);

        if (info.isEnum()) {
            try {
                @SuppressWarnings("rawtypes")
                final Object value = Enum.valueOf((Class<? extends Enum>) info.getJavaType(), strValue);
                list.setSelectedItem(value);
            } catch (final IllegalArgumentException e) {
                throw new ModelInformationException(e.getMessage() + " for parameter: " + info.getName() + ".");
            }
        } else {
            try {
                final int value = Integer.parseInt(strValue);
                list.setSelectedIndex(value);
            } catch (final NumberFormatException e) {
                throw new ModelInformationException(
                        "Invalid value for parameter " + info.getName() + " (not a number).");
            }
        }
        field = list;
    } else if (info.isFile()) {
        field = new JPanel();
        final JTextField textField = new JTextField();

        if (!strValue.isEmpty()) {
            final File file = new File(strValue);
            textField.setText(file.getName());
            textField.setToolTipText(file.getAbsolutePath());
        }

        field.add(textField);
    } else if (info instanceof MasonIntervalParameterInfo) {
        field = new JPanel();
        final JTextField textField = new JTextField(strValue);
        field.add(textField);
    } else {
        field = new JTextField(strValue);
    }

    return field;
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openAnalyseDialog(final int chip) {
    JTextField optionsField = new JTextField();
    JTextField destinationField = new JTextField();

    // compute and try default names for options file.
    // In order : <firmware>.dfr.txt , <firmware>.txt , dfr.txt (or the same for dtx)
    File optionsFile = new File(imageFile[chip].getParentFile(),
            FilenameUtils.getBaseName(imageFile[chip].getAbsolutePath())
                    + ((chip == Constants.CHIP_FR) ? ".dfr.txt" : ".dtx.txt"));
    if (!optionsFile.exists()) {
        optionsFile = new File(imageFile[chip].getParentFile(),
                FilenameUtils.getBaseName(imageFile[chip].getAbsolutePath()) + ".txt");
        if (!optionsFile.exists()) {
            optionsFile = new File(imageFile[chip].getParentFile(),
                    ((chip == Constants.CHIP_FR) ? "dfr.txt" : "dtx.txt"));
            if (!optionsFile.exists()) {
                optionsFile = null;//from   w  w  w  .jav a 2  s .com
            }
        }
    }
    if (optionsFile != null) {
        optionsField.setText(optionsFile.getAbsolutePath());
    }

    // compute default name for output
    File outputFile = new File(imageFile[chip].getParentFile(),
            FilenameUtils.getBaseName(imageFile[chip].getAbsolutePath()) + ".asm");
    destinationField.setText(outputFile.getAbsolutePath());

    final JCheckBox writeOutputCheckbox = new JCheckBox("Write disassembly to file");

    final FileSelectionPanel destinationFileSelectionPanel = new FileSelectionPanel("Destination file",
            destinationField, false);
    destinationFileSelectionPanel.setFileFilter(".asm", "Assembly language file (*.asm)");
    writeOutputCheckbox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            boolean writeToFile = writeOutputCheckbox.isSelected();
            destinationFileSelectionPanel.setEnabled(writeToFile);
            prefs.setWriteDisassemblyToFile(chip, writeToFile);
        }
    });

    writeOutputCheckbox.setSelected(prefs.isWriteDisassemblyToFile(chip));
    destinationFileSelectionPanel.setEnabled(prefs.isWriteDisassemblyToFile(chip));

    FileSelectionPanel fileSelectionPanel = new FileSelectionPanel(
            (chip == Constants.CHIP_FR) ? "Dfr options file" : "Dtx options file", optionsField, false);
    fileSelectionPanel.setFileFilter((chip == Constants.CHIP_FR) ? ".dfr.txt" : ".dtx.txt",
            (chip == Constants.CHIP_FR) ? "Dfr options file (*.dfr.txt)" : "Dtx options file (*.dtx.txt)");
    final JComponent[] inputs = new JComponent[] {
            //new FileSelectionPanel("Source file", sourceFile, false, dependencies),
            fileSelectionPanel, writeOutputCheckbox, destinationFileSelectionPanel,
            makeOutputOptionCheckBox(chip, OutputOption.STRUCTURE, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.ORDINAL, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.PARAMETERS, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.INT40, prefs.getOutputOptions(chip), true),
            makeOutputOptionCheckBox(chip, OutputOption.MEMORY, prefs.getOutputOptions(chip), true),
            new JLabel("(hover over the options for help. See also 'Tools/Options/Disassembler output')",
                    SwingConstants.CENTER) };

    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, inputs, "Choose analyse options",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, JOptionPane.DEFAULT_OPTION)) {
        String outputFilename = writeOutputCheckbox.isSelected() ? destinationField.getText() : null;
        boolean cancel = false;
        if (outputFilename != null) {
            if (new File(outputFilename).exists()) {
                if (JOptionPane.showConfirmDialog(this,
                        "File '" + outputFilename + "' already exists.\nDo you really want to overwrite it ?",
                        "File exists", JOptionPane.YES_NO_OPTION,
                        JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
                    cancel = true;
                }
            }
        }
        if (!cancel) {
            AnalyseProgressDialog analyseProgressDialog = new AnalyseProgressDialog(this,
                    framework.getPlatform(chip).getMemory());
            analyseProgressDialog.startBackgroundAnalysis(chip, optionsField.getText(), outputFilename);
            analyseProgressDialog.setVisible(true);
        }
    }
}

From source file:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfDescriptionPanel.java

/**
 * Builds placeEntry form part.//from   w ww  .j a  v a 2s.  co  m
 */
private PanelBuilder buildPlaceEntry(PanelBuilder builder, CellConstraints cc, PlaceEntry placeEntry,
        boolean flag, int index, boolean filled) {
    JLabel jLabelPlace = new JLabel(this.labels.getString("eaccpf.description.place"));
    builder.add(jLabelPlace, cc.xy(1, rowNb));
    if (placeEntry != null) { //placeEntry part
        TextFieldWithLanguage textFieldWithLanguage = new TextFieldWithLanguage(placeEntry.getContent(),
                placeEntry.getLang());
        JTextField placeEntryTextField = textFieldWithLanguage.getTextField();
        placeEntryTextField.addKeyListener(new CheckPlaceContent(placeEntryTextField, index));
        builder.add(placeEntryTextField, cc.xy(3, rowNb));
        JLabel jLabelLanguage = new JLabel(this.labels.getString("eaccpf.description.selectlanguage"));
        builder.add(jLabelLanguage, cc.xy(5, rowNb));
        JComboBox placeEntryLanguage = textFieldWithLanguage.getLanguageBox();
        placeEntryLanguage.setEnabled(filled);
        builder.add(placeEntryLanguage, cc.xy(7, rowNb));
        appendPlaceEntryPlace(placeEntryTextField, placeEntryLanguage);
    } else { //empty one
        JTextField jTextfieldPlace = new JTextField();
        jTextfieldPlace.addKeyListener(new CheckPlaceContent(jTextfieldPlace, index));
        builder.add(jTextfieldPlace, cc.xy(3, rowNb));
        JLabel jLabelLanguage = new JLabel(this.labels.getString("eaccpf.description.selectlanguage"));
        builder.add(jLabelLanguage, cc.xy(5, rowNb));
        JComboBox jComboboxLanguage = buildLanguageJComboBox(/*flag*/);
        if (!flag) {
            jComboboxLanguage.setSelectedItem("---");
        }
        // Disable combo action.
        jComboboxLanguage.setEnabled(filled);
        builder.add(jComboboxLanguage, cc.xy(7, rowNb));
        appendPlaceEntryPlace(jTextfieldPlace, jComboboxLanguage);
    }
    setNextRow();
    //second line
    JLabel jControlledPlaceLabel = new JLabel(this.labels.getString("eaccpf.description.linkvocabularyplaces"));
    builder.add(jControlledPlaceLabel, cc.xy(1, rowNb));
    JTextField jTextfieldControlledLabelPlace = new JTextField();
    if (placeEntry != null) {
        String vocabLink = placeEntry.getVocabularySource();
        jTextfieldControlledLabelPlace.setText(vocabLink);
    }
    jTextfieldControlledLabelPlace.setEnabled(filled);
    builder.add(jTextfieldControlledLabelPlace, cc.xy(3, rowNb));
    appendPlaceEntryVocabularyPlace(jTextfieldControlledLabelPlace);
    setNextRow();
    //third line
    JLabel jCountryLabel = new JLabel(this.labels.getString("eaccpf.description.country"));
    builder.add(jCountryLabel, cc.xy(1, rowNb));
    JComboBox jComboboxCountry = buildCountryJComboBox();
    if (placeEntry != null) {
        String isoCountry = placeEntry.getCountryCode();
        if (isoCountry != null && !isoCountry.isEmpty()) {
            jComboboxCountry.setSelectedItem(parseIsoToCountry(isoCountry));
        }
    }
    jComboboxCountry.setEnabled(filled);
    builder.add(jComboboxCountry, cc.xy(3, rowNb));
    appendPlaceEntryCountry(jComboboxCountry);
    setNextRow();
    // role of the place has been moved from above to this part because placeEntry is needed 
    // and there is not index (iterator var) by schema (if this part is between "add DATES" and 
    // "add further address details" is impossible to put an index different from '0'
    JLabel jRolePlaceLabel = new JLabel(this.labels.getString("eaccpf.description.roleplace"));
    builder.add(jRolePlaceLabel, cc.xy(1, rowNb));
    TextFieldWithComboBoxEacCpf jComboBoxRolePlace = null;
    if (placeEntry != null) {
        jComboBoxRolePlace = new TextFieldWithComboBoxEacCpf("", placeEntry.getLocalType(),
                TextFieldWithComboBoxEacCpf.TYPE_PLACE_ROLE, this.entityType, this.labels);
    } else {
        jComboBoxRolePlace = new TextFieldWithComboBoxEacCpf("", "",
                TextFieldWithComboBoxEacCpf.TYPE_PLACE_ROLE, this.entityType, this.labels);
    }
    jComboBoxRolePlace.getComboBox().setEnabled(filled);
    builder.add(jComboBoxRolePlace.getComboBox(), cc.xy(3, rowNb));
    appendPlaceEntryRole(jComboBoxRolePlace);
    setNextRow();

    return builder;
}

From source file:com.osparking.osparking.Settings_System.java

private void checkGateNameLength(int gateNo, KeyEvent evt) {
    JTextField gateNameField = (JTextField) getComponentByName("TextFieldGateName" + gateNo);
    String gateName = gateNameField.getText().trim();

    if (gateName.length() > GATE_NAME_LENGTH_MAX) {
        gateNameField.setText(gateNames[gateNo]);
        getToolkit().beep();//from  www . j a  v  a2s  . c om
        JOptionPane.showConfirmDialog(this,
                GATE_NAME_LABEL2.getContent() + " " + System.lineSeparator() + System.lineSeparator()
                        + LIMIT_LABEL.getContent() + GATE_NAME_LENGTH_MAX,
                ERROR_DIALOGTITLE.getContent(), JOptionPane.PLAIN_MESSAGE, WARNING_MESSAGE);
        evt.consume();
    }
}

From source file:com.osparking.osparking.Settings_System.java

private void setPortNumber(DeviceType devType, Object subType, byte gateNo, JTextField portField) {
    JComboBox connTyCBox = ((JComboBox) getComponentByName(devType.name() + gateNo + "_connTypeCBox"));

    if (isSimulator(devType, subType)) {
        int portNo = getPort(devType, gateNo, Globals.versionType) + gateNo;
        portField.setText(Integer.toString(portNo));
        portField.setEnabled(false);//from w w w. j  a v a  2 s . c o  m

        connTyCBox.setSelectedIndex(TCP_IP.ordinal());
        connTyCBox.setEnabled(false);
    } else {
        if (isCarButton(devType, subType, gateNo)) {
            portField.setEnabled(false);
            connTyCBox.setEnabled(false);
        } else {
            portField.setText(devicePort[devType.ordinal()][gateNo]);
            portField.setEnabled(true);
            if (devType == Camera) {
                connTyCBox.setEnabled(false);
            } else {
                connTyCBox.setEnabled(true);
            }
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.FormViewObj.java

/**
 * Helper class to set data into a component
 * @param comp the component to get the data
 * @param data the data to be set into the component
 *///  w  w w  .j  ava 2 s  . com
public static void setDataIntoUIComp(final Component comp, final Object data, final String defaultValue) {
    if (comp instanceof GetSetValueIFace) {
        ((GetSetValueIFace) comp).setValue(data, defaultValue);

    } else if (comp instanceof MultiView) {
        ((MultiView) comp).setData(data);

    } else if (comp instanceof JTextField) {
        JTextField tf = (JTextField) comp;
        tf.setText(data == null ? "" : data.toString());
        tf.setCaretPosition(0);

    } else if (comp instanceof JTextArea) {
        //log.debug(name+" - "+comp.getPreferredSize()+comp.getSize());
        ((JTextArea) comp).setText(data == null ? "" : data.toString());

    } else if (comp instanceof JCheckBox) {
        //log.debug(name+" - "+comp.getPreferredSize()+comp.getSize());
        if (data != null) {
            ((JCheckBox) comp).setSelected((data instanceof Boolean) ? ((Boolean) data).booleanValue()
                    : data.toString().equalsIgnoreCase("true"));
        } else {
            ((JCheckBox) comp).setSelected(false);
        }

    } else if (comp instanceof JLabel) {
        ((JLabel) comp).setText(data == null ? "" : data.toString());

    } else if (comp instanceof JComboBox) {
        setComboboxValue((JComboBox) comp, data);

    } else if (comp instanceof JList) {
        setListValue((JList) comp, data);
    }

    // Reset it's state as not being changes,
    // because setting in data will cause the change flag to be set
    if (comp instanceof UIValidatable && StringUtils.isEmpty(defaultValue)) {
        ((UIValidatable) comp).setChanged(false);
    }
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private List<ParameterInfo> createAndDisplayAParameterPanel(
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title,
        final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify,
        final IModelHandler currentModelHandler) {
    final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(),
            unknownFields = new ArrayList<ParameterMetaData>();
    for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) {
        final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName);
        Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        while (true) {
            try {
                final Field field = modelComponentType.getDeclaredField(fieldName);
                final ParameterMetaData datum = new ParameterMetaData();
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                        continue;
                    final Class<? extends Annotation> type = element.annotationType();
                    datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element);
                    datum.banner = (String) type.getMethod("Title").invoke(element);
                    datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element);
                    datum.imageFileName = (String) type.getMethod("Image").invoke(element);
                    datum.layoutOrder = (Double) type.getMethod("Order").invoke(element);
                }//from  w  w  w  .  j  a v  a2s .  co  m
                datum.parameter = record;
                if (datum.fieldName.trim().isEmpty())
                    datum.fieldName = parameterName.replaceAll("([A-Z])", " $1");
                metadata.add(datum);
                break;
            } catch (final SecurityException e) {
            } catch (final NoSuchFieldException e) {
            } catch (final IllegalArgumentException e) {
            } catch (final IllegalAccessException e) {
            } catch (final InvocationTargetException e) {
            } catch (final NoSuchMethodException e) {
            }
            modelComponentType = modelComponentType.getSuperclass();
            if (modelComponentType == null) {
                ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields);
                break;
            }
        }
    }
    Collections.sort(metadata);
    for (int i = unknownFields.size() - 1; i >= 0; --i)
        metadata.add(0, unknownFields.get(i));

    // initialize single run form
    final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", "");
    appendMinimumWidthHintToPresentation(formBuilder, 550);

    if (parent == null) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                numberOfTurnsField.grabFocus();
            }
        });

        appendBannerToPresentation(formBuilder, "General Parameters");
        appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation");

        formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField);
        formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored);

        appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox);
        appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT,
                advancedChartsCheckBox);
    }

    appendBannerToPresentation(formBuilder, title);

    final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree
            : findParameterInfoNode(parent, false);

    final List<ParameterInfo> info = new ArrayList<ParameterInfo>();

    // Search for a @ConfigurationComponent annotation
    {
        String headerText = "", imagePath = "";
        final Class<?> parentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        for (final Annotation element : parentType.getAnnotations()) { // Proxies
            if (element.annotationType().getName() != ConfigurationComponent.class.getName())
                continue;
            boolean doBreak = false;
            try {
                try {
                    headerText = (String) element.annotationType().getMethod("Description").invoke(element);
                    if (headerText.startsWith("#")) {
                        headerText = (String) parent.getActualType().getMethod(headerText.substring(1))
                                .invoke(parent.getInstance());
                    }
                    doBreak = true;
                } catch (IllegalArgumentException e) {
                } catch (SecurityException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } catch (final Exception e) {
            }
            try {
                imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element);
                doBreak = true;
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
            if (doBreak)
                break;
        }
        if (!headerText.isEmpty())
            appendHeaderTextToPresentation(formBuilder, headerText);
        if (!imagePath.isEmpty())
            appendImageToPresentation(formBuilder, imagePath);
    }

    if (metadata.isEmpty()) {
        // No fields to display.
        appendTextToPresentation(formBuilder, "No configuration is required for this module.");
    } else {
        for (final ParameterMetaData record : metadata) {
            final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter;

            if (!record.banner.isEmpty())
                appendBannerToPresentation(formBuilder, record.banner);
            if (!record.imageFileName.isEmpty())
                appendImageToPresentation(formBuilder, record.imageFileName);
            appendTextToPresentation(formBuilder, record.verboseDescription);

            final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo);
            if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) {
                //               sgi.setParentValue(parent.getActualType());
            }

            final JComponent field;
            final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true);
            Pair<ParameterInfo, JComponent> userData = null;
            JComponent oldField = null;
            if (oldNode != null) {
                userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject();
                oldField = userData.getSecond();
            }

            if (parameterInfo.isBoolean()) {
                field = new JCheckBox();
                boolean value = oldField != null ? ((JCheckBox) oldField).isSelected()
                        : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue();
                ((JCheckBox) field).setSelected(value);
            } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) {
                Object[] elements = null;
                if (parameterInfo.isEnum()) {
                    final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType();
                    elements = type.getEnumConstants();
                } else {
                    final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo;
                    elements = chooserInfo.getValidStrings();
                }
                final JComboBox list = new JComboBox(elements);

                if (parameterInfo.isEnum()) {
                    final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem()
                            : parameterInfo.getValue();
                    list.setSelectedItem(value);
                } else {
                    final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex()
                            : (Integer) parameterInfo.getValue();
                    list.setSelectedIndex(value);
                }

                field = list;
            } else if (parameterInfo instanceof SubmodelInfo) {
                final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                final Object[] elements = new Object[] { "Loading class information..." };
                final JComboBox list = new JComboBox(elements);
                //            field = list;

                final Object value = oldField != null
                        ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem()
                        : new ClassElement(submodelInfo.getActualType(), null);

                new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute();

                final JButton rightButton = new JButton();
                rightButton.setOpaque(false);
                rightButton.setRolloverEnabled(true);
                rightButton.setIcon(SHOW_SUBMODEL_ICON);
                rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO);
                rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS);
                rightButton.setBorder(null);
                rightButton.setToolTipText("Display submodel parameters");
                rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL);
                rightButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        if (parameterInfo instanceof SubmodelInfo) {
                            SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                            int level = 0;

                            showHideSubparameters(list, submodelInfo);

                            List<String> components = new ArrayList<String>();
                            components.add(submodelInfo.getName());
                            while (submodelInfo.getParent() != null) {
                                submodelInfo = submodelInfo.getParent();
                                components.add(submodelInfo.getName());
                                level++;
                            }
                            Collections.reverse(components);
                            final String[] breadcrumbText = components.toArray(new String[components.size()]);
                            for (int i = 0; i < breadcrumbText.length; ++i)
                                breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1");
                            breadcrumb.setPath(
                                    currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"),
                                    breadcrumbText);
                            Style.apply(breadcrumb, dashboard.getCssStyle());

                            // reset all buttons that are nested deeper than this to default color
                            for (int i = submodelButtons.size() - 1; i >= level; i--) {
                                JButton button = submodelButtons.get(i);
                                button.setIcon(SHOW_SUBMODEL_ICON);
                                submodelButtons.remove(i);
                            }

                            rightButton.setIcon(SHOW_SUBMODEL_ICON_RO);
                            submodelButtons.add(rightButton);
                        }
                    }
                });

                field = new JPanel(new BorderLayout());
                field.add(list, BorderLayout.CENTER);
                field.add(rightButton, BorderLayout.EAST);
            } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) {
                field = new JPanel(new BorderLayout());

                String oldName = "";
                String oldPath = "";
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldName = oldTextField.getText();
                    oldPath = oldTextField.getToolTipText();
                } else if (parameterInfo.getValue() != null) {
                    final File file = (File) parameterInfo.getValue();
                    oldName = file.getName();
                    oldPath = file.getAbsolutePath();
                }

                final JTextField textField = new JTextField(oldName);
                textField.setToolTipText(oldPath);
                textField.setInputVerifier(new InputVerifier() {

                    @Override
                    public boolean verify(final JComponent input) {
                        final JTextField inputField = (JTextField) input;
                        if (inputField.getText() == null || inputField.getText().isEmpty()) {
                            final File file = new File("");
                            inputField.setToolTipText(file.getAbsolutePath());
                            hideError();
                            return true;
                        }

                        final File oldFile = new File(inputField.getToolTipText());
                        if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) {
                            hideError();
                            return true;
                        }

                        inputField.setToolTipText("");
                        final File file = new File(inputField.getText().trim());
                        if (file.exists()) {
                            inputField.setToolTipText(file.getAbsolutePath());
                            inputField.setText(file.getName());
                            hideError();
                            return true;
                        } else {
                            final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                            final Point locationOnScreen = inputField.getLocationOnScreen();
                            final JLabel message = new JLabel("Please specify an existing file!");
                            message.setBorder(new LineBorder(Color.RED, 2, true));
                            if (errorPopup != null)
                                errorPopup.hide();
                            errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10,
                                    locationOnScreen.y - 30);
                            errorPopup.show();
                            return false;
                        }
                    }
                });

                final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT);
                browseButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JFileChooser fileDialog = new JFileChooser(
                                !"".equals(textField.getToolTipText()) ? textField.getToolTipText()
                                        : currentDirectory);
                        if (!"".equals(textField.getToolTipText()))
                            fileDialog.setSelectedFile(new File(textField.getToolTipText()));
                        int dialogResult = fileDialog.showOpenDialog(dashboard);
                        if (dialogResult == JFileChooser.APPROVE_OPTION) {
                            final File selectedFile = fileDialog.getSelectedFile();
                            if (selectedFile != null) {
                                currentDirectory = selectedFile.getAbsoluteFile().getParent();
                                textField.setText(selectedFile.getName());
                                textField.setToolTipText(selectedFile.getAbsolutePath());
                            }
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(browseButton, BorderLayout.EAST);
            } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo;

                field = new JPanel(new BorderLayout());

                String oldValueStr = String.valueOf(parameterInfo.getValue());
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldValueStr = oldTextField.getText();
                }

                final JTextField textField = new JTextField(oldValueStr);

                PercentJSlider tempSlider = null;
                if (intervalInfo.isDoubleInterval())
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(),
                            intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr));
                else
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(),
                            intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr));

                final PercentJSlider slider = tempSlider;
                slider.setMajorTickSpacing(100);
                slider.setMinorTickSpacing(10);
                slider.setPaintTicks(true);
                slider.setPaintLabels(true);
                slider.addChangeListener(new ChangeListener() {
                    public void stateChanged(final ChangeEvent _) {
                        if (slider.hasFocus()) {
                            final String value = intervalInfo.isDoubleInterval()
                                    ? String.valueOf(slider.getDoubleValue())
                                    : String.valueOf(slider.getLongValue());
                            textField.setText(value);
                            slider.setToolTipText(value);
                        }
                    }
                });

                textField.setInputVerifier(new InputVerifier() {
                    public boolean verify(JComponent input) {
                        final JTextField inputField = (JTextField) input;

                        try {
                            hideError();
                            final String valueStr = inputField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else
                                    showError(
                                            "Please specify a value between " + intervalInfo.getIntervalMin()
                                                    + " and " + intervalInfo.getIntervalMax() + ".",
                                            inputField);
                                return false;
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else {
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", inputField);
                                    return false;
                                }
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, inputField);
                            return false;
                        }

                    }
                });

                textField.getDocument().addDocumentListener(new DocumentListener() {
                    //               private Popup errorPopup;

                    public void removeUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void insertUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void changedUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    private void textFieldChanged() {
                        if (!textField.hasFocus()) {
                            hideError();
                            return;
                        }

                        try {
                            hideError();
                            final String valueStr = textField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify a value between " + intervalInfo.getIntervalMin()
                                            + " and " + intervalInfo.getIntervalMax() + ".", textField);
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", textField);
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, textField);
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(slider, BorderLayout.SOUTH);
            } else {
                final Object value = oldField != null ? ((JTextField) oldField).getText()
                        : parameterInfo.getValue();
                field = new JTextField(value.toString());
                ((JTextField) field).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        wizard.clickDefaultButton();
                    }
                });
            }

            final JLabel parameterLabel = new JLabel(record.fieldName);

            final String description = parameterInfo.getDescription();
            if (description != null && !description.isEmpty()) {
                parameterLabel.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance();

                        final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel,
                                description, dashboard.getCssStyle());

                        parameterDescriptionPopup.show();
                    }

                });
            }

            if (oldNode != null)
                userData.setSecond(field);
            else {
                final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo,
                        field);
                final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair);
                parentNode.add(newNode);
            }

            if (field instanceof JCheckBox) {
                parameterLabel
                        .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">"
                                + parameterLabel.getText() + "</div></html>");
                formBuilder.append(parameterLabel, field);

                //            appendCheckBoxFieldToPresentation(
                //               formBuilder, parameterLabel.getText(), (JCheckBox) field);
            } else {
                formBuilder.append(parameterLabel, field);
                final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel);
                constraints.vAlign = CellConstraints.TOP;
                constraints.insets = new Insets(5, 0, 0, 0);
                formBuilder.getLayout().setConstraints(parameterLabel, constraints);
            }

            // prepare the parameterInfo for the param sweeps
            parameterInfo.setRuns(0);
            parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF);
            parameterInfo.setValue(batchParameterInfo.getDefaultValue());
            info.add(parameterInfo);
        }
    }
    appendVerticalSpaceToPresentation(formBuilder);

    final JPanel panel = formBuilder.getPanel();
    singleRunParametersPanel.add(panel);

    if (singleRunParametersPanel.getComponentCount() > 1) {
        panel.setBorder(
                BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
                        BorderFactory.createEmptyBorder(0, 5, 0, 5)));
    } else {
        panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    }

    Style.apply(panel, dashboard.getCssStyle());

    return info;
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected void AdjustSounds() {
    final JDialog driver = new JDialog(mainframe, translator.get("MenuSoundsTitle"), true);
    driver.setLayout(new GridBagLayout());

    final JTextField sound_connect = new JTextField(prefs.get("sound_connect", ""), 32);
    final JTextField sound_disconnect = new JTextField(prefs.get("sound_disconnect", ""), 32);
    final JTextField sound_conversion_finished = new JTextField(prefs.get("sound_conversion_finished", ""), 32);
    final JTextField sound_drawing_finished = new JTextField(prefs.get("sound_drawing_finished", ""), 32);

    final JButton change_sound_connect = new JButton(translator.get("MenuSoundsConnect"));
    final JButton change_sound_disconnect = new JButton(translator.get("MenuSoundsDisconnect"));
    final JButton change_sound_conversion_finished = new JButton(translator.get("MenuSoundsFinishConvert"));
    final JButton change_sound_drawing_finished = new JButton(translator.get("MenuSoundsFinishDraw"));

    //final JCheckBox allow_metrics = new JCheckBox(String.valueOf("I want to add the distance drawn to the // total"));
    //allow_metrics.setSelected(allowMetrics);

    final JButton cancel = new JButton(translator.get("Cancel"));
    final JButton save = new JButton(translator.get("Save"));

    GridBagConstraints c = new GridBagConstraints();
    //c.gridwidth=4;    c.gridx=0;  c.gridy=0;  driver.add(allow_metrics,c);

    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;//from  w  w  w .  j  a v a  2s  .c  om
    c.gridx = 0;
    c.gridy = 3;
    driver.add(change_sound_connect, c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 3;
    c.gridx = 1;
    c.gridy = 3;
    driver.add(sound_connect, c);
    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 0;
    c.gridy = 4;
    driver.add(change_sound_disconnect, c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 3;
    c.gridx = 1;
    c.gridy = 4;
    driver.add(sound_disconnect, c);
    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 0;
    c.gridy = 5;
    driver.add(change_sound_conversion_finished, c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 3;
    c.gridx = 1;
    c.gridy = 5;
    driver.add(sound_conversion_finished, c);
    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 0;
    c.gridy = 6;
    driver.add(change_sound_drawing_finished, c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 3;
    c.gridx = 1;
    c.gridy = 6;
    driver.add(sound_drawing_finished, c);

    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 2;
    c.gridy = 12;
    driver.add(save, c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 1;
    c.gridx = 3;
    c.gridy = 12;
    driver.add(cancel, c);

    ActionListener driveButtons = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Object subject = e.getSource();
            if (subject == change_sound_connect)
                sound_connect.setText(SelectFile());
            if (subject == change_sound_disconnect)
                sound_disconnect.setText(SelectFile());
            if (subject == change_sound_conversion_finished)
                sound_conversion_finished.setText(SelectFile());
            if (subject == change_sound_drawing_finished)
                sound_drawing_finished.setText(SelectFile());

            if (subject == save) {
                //allowMetrics = allow_metrics.isSelected();
                prefs.put("sound_connect", sound_connect.getText());
                prefs.put("sound_disconnect", sound_disconnect.getText());
                prefs.put("sound_conversion_finished", sound_conversion_finished.getText());
                prefs.put("sound_drawing_finished", sound_drawing_finished.getText());
                machineConfiguration.SaveConfig();
                driver.dispose();
            }
            if (subject == cancel) {
                driver.dispose();
            }
        }
    };

    change_sound_connect.addActionListener(driveButtons);
    change_sound_disconnect.addActionListener(driveButtons);
    change_sound_conversion_finished.addActionListener(driveButtons);
    change_sound_drawing_finished.addActionListener(driveButtons);

    save.addActionListener(driveButtons);
    cancel.addActionListener(driveButtons);
    driver.getRootPane().setDefaultButton(save);
    driver.pack();
    driver.setVisible(true);
}

From source file:interfaces.InterfazPrincipal.java

private void TablaDeFacturaProductoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaDeFacturaProductoMouseClicked
    final int fila = TablaDeFacturaProducto.getSelectedRow();
    final DefaultTableModel modeloTabla = (DefaultTableModel) TablaDeFacturaProducto.getModel();

    //int identificacion = (int) TablaDeFacturaProducto.getValueAt(fila, 0);        // TODO add your handling code here:
    final JDialog dialogoEdicionProducto = new JDialog(this);
    dialogoEdicionProducto.setTitle("Editar producto");
    dialogoEdicionProducto.setSize(250, 150);
    dialogoEdicionProducto.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel editarTextoPrincipalDialogo = new JLabel("Editar producto");
    c.gridx = 0;//from w ww .ja v  a 2 s  . com
    c.gridy = 0;
    c.gridwidth = 3;
    c.insets = new Insets(15, 40, 10, 0);
    Font textoGrande = new Font("Arial", 1, 18);
    editarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(editarTextoPrincipalDialogo, c);

    c.insets = new Insets(0, 0, 0, 0);
    c.gridwidth = 0;

    c.gridy = 1;
    c.gridx = 0;
    JLabel textoUnidades = new JLabel("Unidades");
    panelDialogo.add(textoUnidades, c);

    c.gridy = 1;
    c.gridx = 1;
    c.gridwidth = 2;
    final JTextField valorUnidades = new JTextField();
    valorUnidades.setText(String.valueOf(modeloTabla.getValueAt(fila, 4)));

    panelDialogo.add(valorUnidades, c);

    c.gridwidth = 1;
    c.gridy = 2;
    c.gridx = 0;
    JButton guardarCambios = new JButton("Guardar");
    panelDialogo.add(guardarCambios, c);

    c.gridy = 2;
    c.gridx = 1;
    JButton eliminarProducto = new JButton("Eliminar");
    panelDialogo.add(eliminarProducto, c);

    c.gridy = 2;
    c.gridx = 2;
    JButton botonCancelar = new JButton("Cerrar");
    panelDialogo.add(botonCancelar, c);
    botonCancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEdicionProducto.dispose();
        }
    });

    eliminarProducto.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            double precio = (double) modeloTabla.getValueAt(fila, 6);
            double precioActual = Double.parseDouble(valorActualFactura.getText());

            precioActual -= precio;
            valorActualFactura.setText(String.valueOf(precioActual));
            modeloTabla.removeRow(fila);

            dialogoEdicionProducto.dispose();

        }
    });
    guardarCambios.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int numeroUnidades = Integer.parseInt(valorUnidades.getText());
                modeloTabla.setValueAt(numeroUnidades, fila, 4);

                double precioARestar = (double) modeloTabla.getValueAt(fila, 6);

                double valorUnitario = Double.parseDouble((String) modeloTabla.getValueAt(fila, 5));

                double precioNuevo = valorUnitario * numeroUnidades;

                modeloTabla.setValueAt(precioNuevo, fila, 6);
                double precioActual = Double.parseDouble(valorActualFactura.getText());
                precioActual -= precioARestar;
                precioActual += precioNuevo;
                valorActualFactura.setText(String.valueOf(precioActual));

                dialogoEdicionProducto.dispose();

            } catch (Exception eve) {
                JOptionPane.showMessageDialog(dialogoEdicionProducto, "Por favor ingrese un valor numrico");
            }
        }
    });

    dialogoEdicionProducto.add(panelDialogo);
    dialogoEdicionProducto.setVisible(true);
}