Search code examples
javaswingjtextfieldjcomboboxitemlistener

How to use a JComboBox to add a JTextField


I need to know how to add a JTextField if one of the JComboBox options is selected, and if the other one is selected I don't want to have that text field there any more.

Here is my code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUI extends JFrame{

    //Not sure if this code is correct

    private JTextField text;

    private JComboBox box;
    private static String[] selector = {"Option 1", "Option 2"};

    public GUI(){
        super("Title");
        setLayout(new FlowLayout());

        box = new JComboBox(selector);
        add(box);

        box.addItemListener(
                new ItemListener(){
                    public void itemStateChanged(ItemEvent e){
                        if(){
                            //what should be in the if statement and what should i type down here to add the
                            //JTextField to the JFrame?
                        }
                    }
                    }
        );
    }
}

Solution

  • Try next example, that should help you:

    import java.awt.BorderLayout;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    public class TestFrame extends JFrame {
    
        public TestFrame(){
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    init();
                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    pack();
                    setVisible(true);
                }
            });
        }
    
        private void init() {
            final JComboBox<String> box = new JComboBox<String>(new String[]{"1","2"});
            final JTextField f = new JTextField(5);
            box.addItemListener(new ItemListener() {
    
                @Override
                public void itemStateChanged(ItemEvent e) {
                    if(e.getStateChange() == ItemEvent.SELECTED){
                        f.setVisible("1".equals(box.getSelectedItem()));
                        TestFrame.this.revalidate();
                        TestFrame.this.repaint();
                    }
                }
            });
    
            add(box,BorderLayout.SOUTH);
            add(f,BorderLayout.NORTH);
        }
    
        public static void main(String... s){
            new TestFrame();
        }
    
    }