// Java Program to create a checkbox
// and add or remove items from it
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class JComboBoxJTextField extends JFrame implements ItemListener, ActionListener {
// frame
static JFrame f;
// label
static JLabel l, l1;
// combobox
static JComboBox c1;
// textfield to add and delete items
static JTextField tf;
// main class
public static void main(String[] args) {
// create a new frame
f = new JFrame("frame");
// create a object
JComboBoxJTextField s = new JComboBoxJTextField();
// set layout of frame
f.setLayout(new FlowLayout());
// array of string contating cities
String s1[] = {};
// create checkbox
c1 = new JComboBox(s1);
// create textfield
tf = new JTextField(16);
// create add and remove buttons
JButton b = new JButton("添加");
// add action listener
b.addActionListener(s);
// add ItemListener
c1.addItemListener(s);
// create a new panel
JPanel p = new JPanel();
// add combobox to panel
p.add(c1);
p.add(tf);
p.add(b);
f.setLayout(new FlowLayout());
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(700, 200);
f.show();
}
// if button is pressed
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
c1.addItem(tf.getText());
}
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println(c1.getSelectedItem());
}
}