如何在JComboBox中选择项目后创建组件。下面是我编码的方式,但它似乎没有做任何事情(即使我将它添加到ActionListener或ItemListener)。我是新来的,如果有什么不对的,请告诉我。如果它已经有答案,请链接我。
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.import javax.swing.JTextField;
public class Tester extends JFrame {
private static final long serialVersionUID = 1L;
private JComboBox<String> cbOne;
private JTextField textfield;
public Tester() {
super("Create jtextfield throught combobox's item");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setLocationRelativeTo(null);
setSize(500, 300);
cbOne = new JComboBox<String>();
cbOne.setModel(new DefaultComboBoxModel<String>(new String[] { "A", "B", "C" }));
cbOne.setSelectedItem(null);
// If you choose an item in combobox, it will create textfield
cbOne.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
if (cbOne.getSelectedItem() != null) {
textfield = new JTextField();
add(textfield);
}
}
});
add(cbOne);
}
public static void main(String[] args) {
new Tester().setVisible(true);
}
}