如何使用JComboBox添加JTextField

时间:2014-04-15 11:04:24

标签: java swing jtextfield jcombobox itemlistener

如果选择了JTextField个选项之一,我需要知道如何添加JComboBox,如果选择了另一个,我不想再拥有该文本字段了。

这是我的代码:

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?
                        }
                    }
                    }
        );
    }
}

1 个答案:

答案 0 :(得分:2)

尝试下一个示例,它可以帮助您:

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();
    }

}