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:edu.ku.brc.specify.plugins.latlon.DDDDPanel.java

/**
 * @param includeEmptyCheck/*from w  w  w . j  a  va  2s  .  c om*/
 * @param txtList
 * @param textTF
 * @param formattedStr
 * @return
 */
protected ErrorType validateState(final boolean includeEmptyCheck,
        final Vector<ValFormattedTextFieldSingle> txtList, final JTextField textTF, final String formattedStr) {
    ErrorType state = validateStateTexFields(includeEmptyCheck, txtList);
    if (hasChanged) {
        textTF.setText(state == ErrorType.Valid || state == ErrorType.Incomplete ? formattedStr : "");
    }
    return state;
}

From source file:br.upe.ecomp.dosa.view.mainwindow.MainWindowActions.java

private boolean chooseDirectory(JTextField textField) {
    JFileChooser fileOpen = new JFileChooser();
    fileOpen.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileOpen.showOpenDialog(this);

    boolean directoryChoosed = false;

    if (fileOpen.getSelectedFile() != null) {
        File directory = new File(fileOpen.getSelectedFile().getAbsolutePath());
        textField.setText(directory.getPath());

        resultFiles = getFilesOnDirectory(directory);
        directoryChoosed = true;//from w  ww.j a  va 2  s. com
    }

    // Codigo para Mac OSX
    // FileDialog fileopen = new FileDialog(this, "Open Results Directory", FileDialog.LOAD);
    // fileopen.setModalityType(ModalityType.DOCUMENT_MODAL);
    //
    // System.setProperty("apple.awt.fileDialogForDirectories", "true");
    // fileopen.setVisible(true);
    // System.setProperty("apple.awt.fileDialogForDirectories", "false");
    //
    // if (fileopen.getFile() != null) {
    // File directory = new File(fileopen.getDirectory(), fileopen.getFile());
    // textField.setText(directory.getPath());
    //
    // resultFiles = getFilesOnDirectory(directory);
    // // List<File> foundFiles = ;
    // // for (File file : foundFiles) {
    // // if (file.getName().endsWith(".txt")) {
    // // resultFiles.add(file);
    // // }
    // // }
    // directoryChoosed = true;
    // }
    return directoryChoosed;
}

From source file:customize.swing.startMain.java

private void setTextValue(JTextField text) {
    jfc.setFileSelectionMode(1);// ?
    int state = jfc.showOpenDialog(null);// ????
    if (state == 1) {
        return;//from  w w w . ja  v  a 2  s. com
    } else {
        File f = jfc.getSelectedFile();// f
        text.setText(f.getAbsolutePath());
    }
}

From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java

public RecursoDialog(final Recurso rec, final AdminResources adminResources) {
    super();//from   www. j  ava 2s.c  om
    setAlwaysOnTop(true);
    setSize(600, 400);

    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            if (cambios) {
                int res = JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION);
                if (res != JOptionPane.CANCEL_OPTION) {
                    e.getWindow().dispose();
                }
            } else {
                e.getWindow().dispose();
            }
        }
    });
    final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId());
    if (r != null) {
        setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador());
    } else {
        setTitle(i18n.getString("Resources.summary.titleWindow.new"));
    }
    setIconImage(getBasicWindow().getFrame().getIconImage());
    JPanel base = new JPanel();
    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    title.setOpaque(false);
    JLabel labelTitulo = null;
    if (r != null) {
        labelTitulo = new JLabel(i18n.getString("Resources.summary"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    } else {
        labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    }
    labelTitulo.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(labelTitulo);
    base.add(title);

    // Nombre
    JPanel mid = new JPanel(new SpringLayout());
    mid.setOpaque(false);
    mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT));
    final JTextField name = new JTextField(25);
    if (r != null) {
        name.setText(r.getNombre());
    }

    name.getDocument().addDocumentListener(changeListener);
    name.setEditable(r == null);
    mid.add(name);

    // patrullas
    final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT);
    mid.add(labelSquads);
    List<Patrulla> pl = PatrullaConsultas.getAll();
    pl.add(0, null);
    final JComboBox squads = new JComboBox(pl.toArray());
    squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX");
    squads.addActionListener(changeSelectionListener);
    squads.setOpaque(false);
    labelSquads.setLabelFor(squads);
    if (r != null) {
        squads.setSelectedItem(r.getPatrullas());
    } else {
        squads.setSelectedItem(null);
    }
    squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true);
    mid.add(squads);

    // // Identificador
    // mid.setOpaque(false);
    // mid.add(new JLabel(i18n.getString("Resources.identificador"),
    // JLabel.RIGHT));
    // final JTextField identificador = new JTextField("");
    // if (r != null) {
    // identificador.setText(r.getIdentificador());
    // }
    // identificador.getDocument().addDocumentListener(changeListener);
    // identificador.setEditable(r == null);
    // mid.add(identificador);
    // Espacio en blanco
    // mid.add(Box.createHorizontalGlue());
    // mid.add(Box.createHorizontalGlue());

    // Tipo
    final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT);
    mid.add(labelTipoRecursos);
    final JComboBox types = new JComboBox(RecursoConsultas.getTipos());
    labelTipoRecursos.setLabelFor(types);
    types.addActionListener(changeSelectionListener);
    if (r != null) {
        types.setSelectedItem(r.getTipo());
    } else {
        types.setSelectedItem(0);
    }
    // types.setEditable(true);
    types.setEnabled(true);
    mid.add(types);

    // Estado Eurocop
    mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT));
    final JTextField status = new JTextField();
    if (r != null && r.getEstadoEurocop() != null) {
        status.setText(r.getEstadoEurocop().getIdentificador());
    }
    status.setEditable(false);
    mid.add(status);

    // Subflota y patrulla
    mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT));
    final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas());
    subfleets.addActionListener(changeSelectionListener);
    if (r != null) {
        subfleets.setSelectedItem(r.getFlotas());
    } else {
        subfleets.setSelectedIndex(0);
    }
    subfleets.setEnabled(true);
    subfleets.setOpaque(false);
    mid.add(subfleets);

    // Referencia humana
    mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT));
    final JTextField rhumana = new JTextField();
    // if (r != null && r.getIncidencias() != null) {
    // rhumana.setText(r.getIncidencias().getReferenciaHumana());
    // }
    rhumana.setEditable(false);
    mid.add(rhumana);

    // dispositivo
    mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT));
    final PlainDocument plainDocument = new PlainDocument() {

        private static final long serialVersionUID = 4929271093724956016L;

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) {
                super.insertString(offs, str, a);
            }
        }
    };
    final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI);
    plainDocument.addDocumentListener(changeListener);
    issi.setEditable(true);
    mid.add(issi);
    mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT));
    final JCheckBox enabled = new JCheckBox("", true);
    enabled.addActionListener(changeSelectionListener);
    enabled.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (enabled.isSelected()) {
                squads.setSelectedIndex(0);
            }
            squads.setEnabled(enabled.isSelected());
        }
    });
    enabled.setEnabled(true);
    enabled.setOpaque(false);
    if (r != null) {
        enabled.setSelected(r.getHabilitado());
    } else {
        enabled.setSelected(true);
    }
    if (r != null && r.getDispositivo() != null) {
        issi.setText(
                StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0'));
    }

    mid.add(enabled);

    // Fecha ultimo gps
    mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT));
    JTextField lastGPS = new JTextField();
    final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r);
    if (lastGPSDateForRecurso != null) {
        lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso));
    }
    lastGPS.setEditable(false);
    mid.add(lastGPS);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    // informacion adicional
    JPanel infoPanel = new JPanel(new SpringLayout());
    final JTextField info = new JTextField(25);
    info.getDocument().addDocumentListener(changeListener);
    infoPanel.add(new JLabel(i18n.getString("Resources.info")));
    infoPanel.add(info);
    infoPanel.setOpaque(false);
    info.setOpaque(false);
    SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18);

    if (r != null) {
        info.setText(r.getInfoAdicional());
    } else {
        info.setText("");
    }
    info.setEditable(true);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18);
    base.add(mid);
    base.add(infoPanel);

    JPanel buttons = new JPanel();
    buttons.setOpaque(false);
    JButton accept = null;
    if (r == null) {
        accept = new JButton("Crear", LogicConstants.getIcon("button_crear"));
    } else {
        accept = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    }
    accept.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (cambios || r == null || r.getId() == null) {
                    boolean shithappens = true;
                    if ((r == null || r.getId() == null)) { // Estamos
                        // creando
                        // uno nuevo
                        if (RecursoConsultas.alreadyExists(name.getText())) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                            shithappens = false;
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText())
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.dispositivoUnico"));
                        }
                    }
                    if (shithappens) {
                        if (name.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreNulo"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.issiUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && !LogicConstants.isNumeric(issi.getText())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noNumerico"));
                            // } else if (identificador.getText().isEmpty())
                            // {
                            // JOptionPane
                            // .showMessageDialog(
                            // RecursoDialog.this,
                            // i18n.getString("admin.recursos.popup.error.identificadorNulo"));
                        } else if (subfleets.getSelectedIndex() == -1) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noSubflota"));
                        } else if (types.getSelectedItem() == null
                                || types.getSelectedItem().toString().trim().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noTipo"));
                        } else {
                            int i = JOptionPane.showConfirmDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"),
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                Recurso recurso = r;

                                if (r == null) {
                                    recurso = new Recurso();
                                }

                                recurso.setInfoAdicional(info.getText());
                                if (issi.getText() != null && issi.getText().length() > 0) {
                                    recurso.setDispositivo(new Integer(issi.getText()));
                                } else {
                                    recurso.setDispositivo(null);
                                }
                                recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString()));
                                if (squads.getSelectedItem() != null && enabled.isSelected()) {
                                    recurso.setPatrullas(
                                            PatrullaConsultas.find(squads.getSelectedItem().toString()));
                                } else {
                                    recurso.setPatrullas(null);
                                }
                                recurso.setNombre(name.getText());
                                recurso.setHabilitado(enabled.isSelected());
                                // recurso.setIdentificador(identificador
                                // .getText());
                                recurso.setTipo(types.getSelectedItem().toString());
                                dispose();

                                RecursoAdmin.saveOrUpdate(recurso);
                                adminResources.refresh(null);

                                PluginEventHandler.fireChange(adminResources);
                            } else if (i == JOptionPane.NO_OPTION) {
                                dispose();
                            }
                        }
                    }
                } else {
                    log.debug("No hay cambios");
                    dispose();
                }

            } catch (Throwable t) {
                log.error("Error guardando un recurso", t);
            }
        }
    });
    buttons.add(accept);

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (cambios) {
                if (JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) {
                    dispose();
                }
            } else {
                dispose();
            }
        }
    });

    buttons.add(cancelar);

    base.add(buttons);

    getContentPane().add(base);
    setLocationRelativeTo(null);
    cambios = false;
    if (r == null) {
        cambios = true;
    }

    pack();

    int x;
    int y;

    Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0);
    Point topLeft = myParent.getLocationOnScreen();
    Dimension parentSize = myParent.getSize();

    Dimension mySize = getSize();

    if (parentSize.width > mySize.width) {
        x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
    } else {
        x = topLeft.x;
    }

    if (parentSize.height > mySize.height) {
        y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
    } else {
        y = topLeft.y;
    }

    setLocation(x, y);
    cambios = false;
}

From source file:com.all.login.view.NewAccountFormPanel.java

private void capitalizeText(JTextField field) {
    field.setText(WordUtils.capitalizeFully(field.getText()));
}

From source file:com.comcast.cats.vision.CATSVisionTest.java

protected int[] searchAvailableSettopsAndGetRowsSelected(Window mainWindow, String keyword) {

    JPanel configPanel = CommonTestUtils.getConfigPanel(mainWindow);

    final Button searchButton = CommonTestUtils.getConfigPanelButton(mainWindow, "searchButton");

    final JTextField searchTextField = CommonTestUtils.getConfigPanelTextField(mainWindow, "searchTextField");

    Table uiTable = CommonTestUtils.getTableFromConfigPanel(configPanel, "availableSettopsScrollPane",
            "Available Settops", 0);

    assertTrue(//from   w w w.  j av a 2 s.  co  m
            "Expected header for the table is - " + Arrays.asList(CommonTestUtils.AVAILABLE_TABLE_STRINGS)
                    + "\n but actual header is - " + Arrays.asList(uiTable.getHeader().getColumnNames()),
            Arrays.equals(uiTable.getHeader().getColumnNames(), CommonTestUtils.AVAILABLE_TABLE_STRINGS));

    int numberOfRows = (uiTable.getRowCount() > 0) ? uiTable.getRowCount() : 0;

    assertTrue("'Available Settops' donot have any rows", numberOfRows > 0);

    searchTextField.setText(keyword);

    searchButton.click();

    Table uiTableAfterSearch = CommonTestUtils.getTableFromConfigPanel(configPanel,
            "availableSettopsScrollPane", "Available Settops", 0);

    int rows = (uiTableAfterSearch.getRowCount() > 0) ? uiTableAfterSearch.getRowCount() : 0;

    assertTrue("No matching settop found", rows > 0);

    uiTableAfterSearch.selectRow(0);

    searchTextField.setText("");

    searchButton.click();

    uiTableAfterSearch = CommonTestUtils.getTableFromConfigPanel(configPanel, "availableSettopsScrollPane",
            "Available Settops", 0);

    JTable table = uiTableAfterSearch.getAwtComponent();

    int numberOfRowsAfterSearch = (table.getSelectedRows().length > 0) ? table.getSelectedRows().length : 0;
    assertTrue(numberOfRowsAfterSearch <= numberOfRows);
    return table.getSelectedRows();
}

From source file:es.emergya.ui.gis.popups.SaveGPXDialog.java

private SaveGPXDialog(final List<Layer> capas) {
    super("Consulta de Posiciones GPS");
    setResizable(false);//from   w  w w  .j a  v a2  s  .  c  o m
    setAlwaysOnTop(true);
    try {
        setIconImage(((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getIconImage());
    } catch (Throwable e) {
        LOG.error("There is no icon image", e);
    }

    this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    JPanel dialogo = new JPanel(new BorderLayout());
    dialogo.setBackground(Color.WHITE);
    dialogo.setBorder(new EmptyBorder(10, 10, 10, 10));

    JPanel central = new JPanel(new FlowLayout());
    central.setOpaque(false);
    final JTextField nombre = new JTextField(15);
    nombre.setEditable(false);
    central.add(nombre);
    final JButton button = new JButton("Examinar...", LogicConstants.getIcon("button_nuevo"));
    central.add(button);
    final JButton aceptar = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showSaveDialog(SaveGPXDialog.this) == JFileChooser.APPROVE_OPTION) {
                nombre.setText(fileChooser.getSelectedFile().getAbsolutePath());
                aceptar.setEnabled(true);
            }
        }
    });

    dialogo.add(central, BorderLayout.CENTER);

    JPanel botones = new JPanel(new FlowLayout());
    botones.setOpaque(false);

    aceptar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String base_url = nombre.getText() + "_";
            for (Layer layer : capas) {
                if (layer instanceof GpxLayer) {
                    GpxLayer gpxLayer = (GpxLayer) layer;
                    File f = new File(base_url + gpxLayer.name + ".gpx");

                    boolean sobreescribir = !f.exists();

                    try {
                        while (!sobreescribir) {
                            String original = f.getCanonicalPath();
                            f = checkFileOverwritten(nombre, f);
                            sobreescribir = !f.exists() || original.equals(f.getCanonicalPath());
                        }
                    } catch (NullPointerException t) {
                        log.debug("Cancelando creacion de fichero: " + t);
                        sobreescribir = false;
                    } catch (Throwable t) {
                        log.error("Error comprobando la sobreescritura", t);
                        sobreescribir = false;
                    }

                    if (sobreescribir) {
                        try {
                            f.createNewFile();
                        } catch (IOException e1) {
                            log.error(e1, e1);
                        }
                        if (!(f.isFile() && f.canWrite()))
                            JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                    "No tengo permiso para escribir en " + f.getAbsolutePath());
                        else {
                            try {
                                OutputStream out = new FileOutputStream(f);
                                GpxWriter writer = new GpxWriter(out);
                                writer.write(gpxLayer.data);
                                out.close();
                            } catch (Throwable t) {
                                log.error("Error al escribir el gpx", t);
                                JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                        "Ocurri un error al escribir en " + f.getAbsolutePath());
                            }
                        }
                    } else
                        log.error("Por errores anteriores no se escribio el fichero");
                } else
                    log.error("Una de las capas no era gpx: " + layer.name);
            }
            SaveGPXDialog.this.dispose();

        }

        private File checkFileOverwritten(final JTextField nombre, File f) throws Exception {
            String nueva = JOptionPane.showInputDialog(nombre, i18n.getString("savegpxdialog.overwrite"),
                    "Sobreescribir archivo", JOptionPane.QUESTION_MESSAGE, null, null, f.getCanonicalPath())
                    .toString();
            log.debug("Nueva ruta: " + nueva);
            return new File(nueva);
        }
    });

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

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

    aceptar.setEnabled(false);
    botones.add(aceptar);
    botones.add(cancelar);
    dialogo.add(botones, BorderLayout.SOUTH);

    add(dialogo);
    setPreferredSize(new Dimension(300, 200));
    pack();

    int x;
    int y;

    Container myParent;
    try {
        myParent = ((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getContentPane();
        java.awt.Point topLeft = myParent.getLocationOnScreen();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        if (parentSize.width > mySize.width)
            x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
        else
            x = topLeft.x;

        if (parentSize.height > mySize.height)
            y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
        else
            y = topLeft.y;

        setLocation(x, y);
    } catch (Throwable e1) {
        LOG.error("There is no basic window!", e1);
    }

    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }

        @Override
        public void windowClosing(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }
    });
}

From source file:com.smanempat.controller.ControllerClassification.java

public void chooseFile(ActionEvent evt, JTextField txtFileDirectory, JTextField txtNumberOfK,
        JLabel labelJumlahData, JButton buttonProses, JTable tablePreview) {
    try {/*from ww  w .  j  av a  2 s. co m*/
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Excel File", "xls",
                "xlsx");
        fileChooser.setFileFilter(fileNameExtensionFilter);

        if (fileChooser.showOpenDialog(fileChooser) == JFileChooser.APPROVE_OPTION) {
            txtFileDirectory.setText(fileChooser.getSelectedFile().getAbsolutePath());
            System.out.println("Good, File Chooser runing well!");
            if (txtFileDirectory.getText().endsWith(".xls") || txtFileDirectory.getText().endsWith(".xlsx")) {
                showOnTable(evt, txtFileDirectory, tablePreview);
                labelJumlahData.setText(tablePreview.getRowCount() + " Data");
                txtNumberOfK.setEnabled(true);
                txtNumberOfK.requestFocus();
                buttonProses.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(null,
                        "File dataset harus file spreadsheet dengan ekstensi *xls atau *.xlsx!", "Error",
                        JOptionPane.INFORMATION_MESSAGE, new ImageIcon("src/com/smanempat/image/fail.png"));
                txtFileDirectory.setText("");
                chooseFile(evt, txtFileDirectory, txtNumberOfK, labelJumlahData, buttonProses, tablePreview);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:krasa.formatter.plugin.ProjectSettingsForm.java

public ProjectSettingsForm(final Project project) {
    DONATEButton.setBorder(BorderFactory.createEmptyBorder());
    DONATEButton.setContentAreaFilled(false);
    this.project = project;
    JToggleButton[] modifiableButtons = new JToggleButton[] { useDefaultFormatter, useEclipseFormatter,
            optimizeImportsCheckBox, enableJavaFormatting, doNotFormatOtherFilesRadioButton,
            formatOtherFilesWithExceptionsRadioButton, formatSelectedTextInAllFileTypes, enableJSFormatting,
            enableCppFormatting, importOrderConfigurationManualRadioButton,
            importOrderConfigurationFromFileRadioButton, enableGWTNativeMethodsCheckBox };
    for (JToggleButton button : modifiableButtons) {
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                updateComponents();//from   ww  w. jav  a 2  s  .co  m
            }
        });
    }

    JTextField[] modifiableFields = new JTextField[] { pathToEclipsePreferenceFileJava,
            pathToEclipsePreferenceFileJS, pathToEclipsePreferenceFileCpp, disabledFileTypes, importOrder,
            pathToImportOrderPreferenceFile };
    for (JTextField field : modifiableFields) {
        field.getDocument().addDocumentListener(new DocumentAdapter() {
            protected void textChanged(DocumentEvent e) {
                updateComponents();
            }
        });
    }

    eclipsePreferenceFilePathJavaBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToEclipsePreferenceFileJava);
        }
    });
    pathToImportOrderPreferenceFileBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToImportOrderPreferenceFile);
        }
    });
    eclipsePreferenceFilePathJSBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToEclipsePreferenceFileJS);
        }
    });
    eclipsePreferenceFilePathCppBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            browseForFile(pathToEclipsePreferenceFileCpp);
        }
    });

    rootComponent.addAncestorListener(new AncestorListener() {
        public void ancestorAdded(AncestorEvent event) {
            // Called when component becomes visible, to ensure that the
            // popups
            // are visible when the form is shown for the first time.
            updateComponents();
        }

        public void ancestorRemoved(AncestorEvent event) {
        }

        public void ancestorMoved(AncestorEvent event) {
        }
    });

    pathToEclipsePreferenceFileJava.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            setJavaFormatterProfileModel();
        }
    });

    pathToEclipsePreferenceFileJS.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            setJavaScriptFormatterProfileModel();
        }
    });

    pathToEclipsePreferenceFileCpp.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            setCppFormatterProfileModel();
        }
    });

    newProfile.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (isModified(displayedSettings)) {
                createConfirmation("Profile was modified, save changes to current profile?", "Yes", "No",
                        new Runnable() {
                            @Override
                            public void run() {
                                apply();
                                createProfile();
                            }
                        }, new Runnable() {
                            @Override
                            public void run() {
                                importFrom(displayedSettings);
                                createProfile();
                            }
                        }, 0).showInFocusCenter();
            } else {
                createProfile();
            }
        }

        private void createProfile() {
            Settings settings = GlobalSettings.getInstance().newSettings();
            refreshProfilesModel();
            profiles.setSelectedItem(settings);
        }
    });
    copyProfile.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (isModified(displayedSettings)) {
                ListPopup confirmation = createConfirmation(
                        "Profile was modified, save changes to current profile?", "Yes", "No", new Runnable() {
                            @Override
                            public void run() {
                                apply();
                                copyProfile();
                            }
                        }, new Runnable() {
                            @Override
                            public void run() {
                                importFrom(displayedSettings);
                                copyProfile();
                            }
                        }, 0);

                confirmation.showInFocusCenter();
            } else {
                copyProfile();
            }
        }

        private void copyProfile() {
            Settings settings = GlobalSettings.getInstance().copySettings(displayedSettings);
            refreshProfilesModel();
            profiles.setSelectedItem(settings);

        }
    });
    setJavaFormatterProfileModel();
    setJavaScriptFormatterProfileModel();
    setCppFormatterProfileModel();

    profilesModel = createProfilesModel();
    profiles.setModel(profilesModel);
    profiles.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // && isSameId()
            if (displayedSettings != null && getSelectedItem() != null && isModified(displayedSettings)) {
                showConfirmationDialogOnProfileChange();
            } else if (displayedSettings != null && getSelectedItem() != null) {
                importFromInternal(getSelectedItem());
            }
        }

    });

    profiles.setRenderer(new ListCellRendererWrapper() {
        @Override
        public void customize(JList jList, Object value, int i, boolean b, boolean b1) {
            if (value != null) {
                setText(((Settings) value).getName());
            }
        }
    });
    rename.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final JTextField content = new JTextField();
            content.setText(displayedSettings.getName());
            JBPopup balloon = PopupFactoryImpl.getInstance().createComponentPopupBuilder(content, content)
                    .createPopup();
            balloon.setMinimumSize(new Dimension(200, 20));
            balloon.addListener(new JBPopupListener() {
                @Override
                public void beforeShown(LightweightWindowEvent event) {
                }

                @Override
                public void onClosed(LightweightWindowEvent event) {
                    displayedSettings.setName(content.getText());
                }
            });
            balloon.showUnderneathOf(rename);
        }
    });
    delete.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int selectedIndex = profiles.getSelectedIndex();
            GlobalSettings.getInstance().delete(getSelectedItem(), getProject());
            profiles.setModel(profilesModel = createProfilesModel());
            int itemCount = profiles.getItemCount();
            if (selectedIndex < itemCount && selectedIndex >= 0) {
                Object itemAt = profiles.getItemAt(selectedIndex);
                importFromInternal((Settings) itemAt);
                profiles.setSelectedIndex(selectedIndex);
            }
            if (selectedIndex == itemCount && selectedIndex - 1 >= 0) {
                Object itemAt = profiles.getItemAt(selectedIndex - 1);
                importFromInternal((Settings) itemAt);
                profiles.setSelectedIndex(selectedIndex - 1);
            } else {
                Settings defaultSettings = GlobalSettings.getInstance().getDefaultSettings();
                importFromInternal(defaultSettings);
                profiles.setSelectedItem(defaultSettings);
            }

        }
    });
    DONATEButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BareBonesBrowserLaunch.openURL(
                    "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=75YN7U7H7D7XU&lc=CZ&item_name=Eclipse%20code%20formatter%20%2d%20IntelliJ%20plugin%20%2d%20Donation&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHostedGuest");
        }
    });
    helpButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BareBonesBrowserLaunch
                    .openURL("http://code.google.com/p/eclipse-code-formatter-intellij-plugin/wiki/HowTo");
        }
    });
    ;
    homepage.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BareBonesBrowserLaunch.openURL("http://plugins.intellij.net/plugin/?idea&id=6546");
        }
    });
}

From source file:MainClass.java

public MainClass() {
    final JTree tree;
    final JTextField jtf;

    DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

    DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
    top.add(a);/*w w w  .j a  va2 s.co  m*/
    DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
    a.add(a1);
    DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
    a.add(a2);

    DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
    top.add(b);
    DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
    b.add(b1);
    DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
    b.add(b2);
    DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
    b.add(b3);

    tree = new JTree(top);

    JScrollPane jsp = new JScrollPane(tree);

    add(jsp, BorderLayout.CENTER);

    jtf = new JTextField("", 20);
    add(jtf, BorderLayout.SOUTH);

    tree.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent me) {
            TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
            if (tp != null)
                jtf.setText(tp.toString());
            else
                jtf.setText("");
        }
    });

}