How to validate if a String already exists in the Jcombobox list?

Asked

Viewed 425 times

0

It follows the code that I am locked, I wonder how do I validate if a directory that I will add, already exists in JComboBox?

package view;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import javax.swing.JSeparator;

public class JanelaJavaEasyDirectoryMinimizado extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    JanelaJavaEasyDirectoryMinimizado frame = new JanelaJavaEasyDirectoryMinimizado();
                    frame.setVisible(true);
                    frame.setLocationRelativeTo(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public JanelaJavaEasyDirectoryMinimizado() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 308);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        //Abaixo é para adicionar um novo diretório ao comboBox
        JLabel lblDiretorio = new JLabel("Diretório:");
        lblDiretorio.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblDiretorio.setBounds(59, 40, 68, 14);
        contentPane.add(lblDiretorio);

        JTextField campoNovoDiretorio = new JTextField();
        campoNovoDiretorio.setBounds(144, 38, 264, 20);
        contentPane.add(campoNovoDiretorio);
        campoNovoDiretorio.setColumns(10);

        JButton btnAddDiretorio = new JButton("Adicionar diretório");
        btnAddDiretorio.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String novoDiretorio = campoNovoDiretorio.getText();

                JComboBox campoDiretorio = SingletonComboDiretorio.getInstance();
                campoDiretorio.addItem(novoDiretorio);

                DefaultComboBoxModel model = (DefaultComboBoxModel)campoDiretorio.getModel();

                if (novoDiretorio.isEmpty())
                    throw new RuntimeException();
                else if (model.getIndexOf(campoDiretorio) != -1) //PROBLEMA DE VALIDAÇÃO NESSA PARTE
                    JOptionPane.showMessageDialog(null, "Diretório ja existe, adicione outro!");
                else
                    JOptionPane.showMessageDialog(null, "Diretório adicionado à lista:\n " + novoDiretorio, "Mensagem",
                            1);
            }
        });
        btnAddDiretorio.setBounds(143, 68, 264, 25);
        contentPane.add(btnAddDiretorio);

        //Abaixo é área para poder selecionar o diretório que contém no comboBox e o nome da pasta.
        JLabel lblDiretrio = new JLabel("Diret\u00F3rio:");
        lblDiretrio.setToolTipText("Selecione um diret\u00F3rio.");
        lblDiretrio.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblDiretrio.setBounds(59, 140, 68, 14);
        contentPane.add(lblDiretrio);

        JComboBox campoDiretorio = SingletonComboDiretorio.getInstance();
        campoDiretorio.setModel(new DefaultComboBoxModel(new String[] { "Sem diretório" }));
        campoDiretorio.setBounds(144, 140, 264, 20);
        contentPane.add(campoDiretorio);

        JLabel lblNomeDoArquivo = new JLabel("Nome da pasta:");
        lblNomeDoArquivo.setToolTipText("Insira o nome da pasta que deseja criar.");
        lblNomeDoArquivo.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblNomeDoArquivo.setBounds(15, 170, 112, 14);
        contentPane.add(lblNomeDoArquivo);

        JTextField campoNomeDoArquivo = new JTextField();
        campoNomeDoArquivo.setBounds(144, 170, 264, 20);
        contentPane.add(campoNomeDoArquivo);
        campoNomeDoArquivo.setColumns(10);

        JButton btnCriarDiretrio = new JButton("Criar diret\u00F3rio");
        btnCriarDiretrio.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String nomeDirDesejado = (String) campoDiretorio.getSelectedItem();

                String nomePasta = campoNomeDoArquivo.getText();

                File novaPasta = new File(nomeDirDesejado, nomePasta);
                novaPasta.mkdir();

                if (nomePasta.isEmpty())
                    throw new IllegalArgumentException();
                else
                    JOptionPane.showMessageDialog(null, "Diretório criado em:\n" + nomeDirDesejado + "\\" + nomePasta, "Mensagem", 1);

            }
        });
        btnCriarDiretrio.setBounds(150, 200, 126, 23);
        contentPane.add(btnCriarDiretrio);

        JSeparator separator = new JSeparator();
        separator.setBounds(0, 115, 434, 14);
        contentPane.add(separator);

        JLabel lblRenanNarciso = new JLabel("Renan Narciso - 2017");
        lblRenanNarciso.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblRenanNarciso.setBounds(144, 244, 155, 14);
        contentPane.add(lblRenanNarciso);

    }
}

//Classe criada sob o padrão de projeto Singleton para poder usar um JComboBox estatático.
class SingletonComboDiretorio {

    private static JComboBox compoDiretorio;

    private SingletonComboDiretorio() {

    }

    public static synchronized JComboBox getInstance() {
        if (compoDiretorio == null) {
            compoDiretorio = new JComboBox();
        }
        return compoDiretorio;
    }
}
  • A topic I have doubt when entering data at runtime. This topic I have doubt when validating a string with some combobox data. I’ll edit it and put the code...

  • Code posted in topic.

  • You want to check whether the string is contained in the list of combobox items or only the item that is selected in the combo?

  • check if the string I’m adding currently already has in the items contained in the combobox

1 answer

2


The problem that occurs is that you are passing to the method indexOf check if already existed in the list the object that represents its combo and not the string newly typed. There is another problem also in the code, you add the name of the directory in the combo before validating it, IE, if it is repeated or blank, will be added in the same way, making useless the conditions that follow on Listener button btnAddDiretorio.

The correct form of actionPerfomed it should be like this:

btnAddDiretorio.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        String novoDiretorio = campoNovoDiretorio.getText();

        JComboBox campoDiretorio = SingletonComboDiretorio.getInstance();
        DefaultComboBoxModel model = (DefaultComboBoxModel) campoDiretorio.getModel();

        if (novoDiretorio.isEmpty())
            JOptionPane.showMessageDialog(null, "Nome do diretório não pode ser em branco!");
        else if (model.getIndexOf(novoDiretorio) != -1) {
            JOptionPane.showMessageDialog(null, "Diretório ja existe, adicione outro!");
        } else {
            campoDiretorio.addItem(novoDiretorio);
            JOptionPane.showMessageDialog(null, "Diretório adicionado à lista:\n " + novoDiretorio, "Mensagem",
                    1);
        }
    }
});

Remembering that the method getIndexOf(Object anItem) returns the item index if it exists in the JComboBox, and -1 if it has not been located, so the validation is to check if it returns other than -1.

It is important to note that in case you have created a ComboModel own, you must change the cast of DefaultComboBoxModel for your ComboModel.

  • Po, I did this here is continued entering repeated directories.

  • @Renannarciso there is probably some different detail, if you have an extra space this method will not validate as repeated. I noticed that the information comes from a text field, it can be this. Try to copy exactly a directory that already exists and paste into the field to see if it passes.

  • no if, instead of me putting != -1, I put == -1 and appeared the window stating that the directory already exists. Well the message appears but the directory is added. I think doing this part ai of the code in a Try/catch would solve, no?

  • I mean, with the code == -1 even tense n placed no item on the combobox, it appears to msg saying q already has such an item

  • @Renannarciso -1 is the result of the comparison, only returns this if the item does not exist in the combo. If it already exists, it returns his Index in the combo list, so the comparison needs to return different from -1, because it means it already exists. There is no need to Try/catch, just that there solves the duplicate problem, re-read my previous comment, the cause is not this logic but how the texts are coming.

  • Yes, I read your previous comment. I put the same directory followed by the other and passes

  • @Renannarciso then it will be necessary a reproducible and executable example of your code to test where the problem is probably.

  • How do I send a playable file here?

  • @Renannarciso you can add in question by clicking on edit

  • Okay, when I get back from work, I’m in charge here.

  • Code edited and added to the post. The problem is on line 80. PS: minimized the code to all give in only one Jframe and in the same class.

  • @Renannarciso located the problem, see the edition. There are other problems in your code, I suggest you check the button actionPerformed btnCriarDiretrio he’s also in trouble. I just didn’t show in the answer because it would come out of what was asked.

  • Very good, thank you! I just didn’t quite understand that line as you said above... model.getIndexOf(novoDiretorio) != -1 and why you had to use the class DefaultComboBoxModel to create a Combobox

  • 1

    @Renannarciso what this line does is to recover the combo model, not create it again. Every swing component has a model that defines how the items will be displayed within it, the defaultcomboboxmodel is that stores all items of the combo, as well as operations with them (addition, removal, editing), so I recovered an instance of it, because to check if an item exists, just refer to the model.[...]

  • 1

    @Renannarciso[...] when you do combo.addItem() java actually calls the model of this combo and makes the addition in it, because the combo itself does not store its items.

  • If getIndexOf returns -1 is true, so if the directory already exists in the combo, it returns -1. Then Jopitionpane is executed, correct?

  • 1

    @Renannarciso see the line I explain again: The getIndexOf(Object anItem) method returns the input of an element, if it exists in the Jcombobox model, and -1 if it has not been located. That is, if it finds an object in the model, and this object is the fourth of the list, it will return 3 (lists beginning with 0 in java), if not, returns -1.

  • @Renannarciso the answer answered you? If yes, you can mark it as accepted by clicking on v on the left side, thus it stands as a reference to other people with similar problems :)

Show 13 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.