Repository navigation
Expand file tree
/
Copy pathJComboBoxTutorial.java
More file actions
62 lines (54 loc) · 1.51 KB
/
Copy pathJComboBoxTutorial.java
File metadata and controls
62 lines (54 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class JComboBoxTutorial {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JComboBox<String> comboBox = new JComboBox<String>();
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
JTextField txtAdd = new JTextField(15);
JButton btnAdd = new JButton("Add");
JButton btnRemove = new JButton("Remove");
String selectedValue;
public JComboBoxTutorial() {
comboBox.setModel(model);
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
selectedValue = model.getSelectedItem().toString();
}
}
});
btnRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.removeElement(selectedValue);
}
});
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.addElement(txtAdd.getText());
}
});
panel.add(txtAdd);
panel.add(btnAdd);
panel.add(comboBox);
panel.add(btnRemove);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JComboBoxTutorial();
}
});
}
}