summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java
blob: 465be0234296b450afab00aa735a9f360f5f08a8 (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
package bjc.utils.gui.panels;

import java.awt.BorderLayout;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;

import bjc.funcdata.ListEx;
import bjc.utils.gui.layout.AutosizeLayout;
import bjc.utils.gui.layout.HLayout;

/**
 * A panel that allows you to select choices from a dropdown list
 *
 * @author ben
 *
 */
public class DropdownListPanel extends JPanel {
	private static final long serialVersionUID = 2719963952350133541L;

	/**
	 * Create a new dropdown list panel
	 *
	 * @param <T>
	 *                The type of items in the dropdown list
	 * @param type
	 *                The label of the type of items in the list
	 * @param model
	 *                The model to put items into
	 * @param choices
	 *                The items to choose from
	 */
	public <T> DropdownListPanel(final String type, final DefaultListModel<T> model,
			final ListEx<T> choices) {
		setLayout(new AutosizeLayout());

		final JPanel itemInputPanel = new JPanel();
		itemInputPanel.setLayout(new BorderLayout());

		final JPanel addItemPanel = new JPanel();
		addItemPanel.setLayout(new HLayout(2));

		final JComboBox<T> addItemBox = new JComboBox<>();
		choices.forEach(addItemBox::addItem);

		final JButton addItemButton = new JButton("Add " + type);

		addItemPanel.add(addItemBox);
		addItemPanel.add(addItemButton);

		final JList<T> itemList = new JList<>(model);
		itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		final JButton removeItemButton = new JButton("Remove " + type);

		addItemButton.addActionListener(ev -> {
			model.addElement(addItemBox.getItemAt(addItemBox.getSelectedIndex()));
		});

		removeItemButton.addActionListener(ev -> {
			model.remove(itemList.getSelectedIndex());
		});

		itemInputPanel.add(addItemPanel, BorderLayout.PAGE_START);
		itemInputPanel.add(itemList, BorderLayout.CENTER);
		itemInputPanel.add(removeItemButton, BorderLayout.PAGE_END);

		add(itemInputPanel);
	}
}