summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleListPanel.java
blob: 3e4e0ad9243fb434b26bf422d1e3c884332c66a9 (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
75
76
77
78
79
80
81
package bjc.utils.gui;

import java.awt.BorderLayout;
import java.util.function.Consumer;
import java.util.function.Predicate;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

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

public class SimpleListPanel extends JPanel {
	private static final long serialVersionUID = 2719963952350133541L;

	public SimpleListPanel(String itemType,
			DefaultListModel<String> listModel,
			Predicate<String> itemVerifier,
			Consumer<String> onVerificationFailure) {
		setLayout(new AutosizeLayout());

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

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

		JTextField addItemField = new JTextField(255);
		JButton addItemButton = new JButton("Add " + itemType);

		addItemPanel.add(addItemField);
		addItemPanel.add(addItemButton);

		JList<String> itemList = new JList<>(listModel);
		itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		JScrollPane listScroller = new JScrollPane(itemList);

		JButton removeItemButton = new JButton("Remove " + itemType);

		addItemButton.addActionListener((ev) -> {
			addItem(listModel, itemVerifier, onVerificationFailure,
					addItemField);
		});

		addItemField.addActionListener((ev) -> {
			addItem(listModel, itemVerifier, onVerificationFailure,
					addItemField);
		});

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

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

		add(itemInputPanel);
	}

	private static void addItem(DefaultListModel<String> listModel,
			Predicate<String> itemVerifier,
			Consumer<String> onVerificationFailure,
			JTextField addItemField) {
		String potentialItem = addItemField.getText();

		if (itemVerifier == null || itemVerifier.test(potentialItem)) {
			listModel.addElement(potentialItem);
		} else {
			onVerificationFailure.accept(potentialItem);
		}

		addItemField.setText("");
	}
}