How to use a JComboBox from one class to another?

1

I want to create two screens, one registers the values of the JCombobox and in the other I use the values. I can recover the Combobox but it does not appear any value.

Class of registration

public class Combo extends JFrame{

    private JButton ok,proxima;
    private JTextField texto;
    private JComboBox<String> meucombo;


    public JComboBox getMeucombo() {
        return meucombo;
    }

    Combo() {

        super("ComboBox");
        mCombo();
    }

    private void mCombo() {

        setLayout(new BorderLayout());

        acaoBotao acao = new acaoBotao();
        outroBotao outroBotao = new outroBotao();

        meucombo = new JComboBox<String>();

        proxima = new JButton("proxima");
        proxima.addActionListener(outroBotao);

        ok = new JButton("OK");
        ok.addActionListener(acao);

        texto = new JTextField();

        add(meucombo, BorderLayout.NORTH);
        add(texto, BorderLayout.CENTER);
        add(ok, BorderLayout.SOUTH);
        add(proxima,BorderLayout.EAST);


    }

    private class acaoBotao implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {


            meucombo.addItem(texto.getText());
            texto.setText("");

        }
    }

    private class outroBotao implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {

            Teste teste = new Teste();
            teste.setVisible(true);
        }
    }
}

Another class

public class Teste extends JFrame {

    Teste(){

        super("teste");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(600,600);
        setVisible(true);
        Combo combo = new Combo();
        JComboBox mcombo = combo.getMeucombo();
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        add(mcombo);

    }

}
    
asked by anonymous 29.09.2017 / 19:41

1 answer

1

You can pass the combo as an argument to the constructor of the new class:

private class outroBotao implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {

        Teste teste = new Teste(meucombo);
        teste.setVisible(true);
    }

And in the Test class:

public class Teste extends JFrame {

    Teste(JComboBox combo){

        super("teste");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(600,600);
        setVisible(true);
        Combo combo = new Combo();
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        add(combo);

    }

}

But I do not think this approach is good. The component must be built on the same screen as it is part of. What would be more appropriate, I believe, is to persist the combo data in some way and use this data on the new screen, so you do not have to create the component in one place and add it to another.

    
29.09.2017 / 19:44