import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
@SuppressWarnings("serial")
public class ListPanel extends JPanel {
private DefaultListModel<String> model = new DefaultListModel<>();
private JList<String> list = new JList<>(model);
private JScrollPane scroll = new JScrollPane(list);
private JTextField input = new JTextField();
private JButton add = new JButton("add");
private JButton del = new JButton("delete");
private JLabel output = new JLabel();
public ListPanel(int width, int height) {
createGui(width, height);
add.addActionListener(e -> {
String text = input.getText();
if (text.length() > 0 && !model.contains(text)) {
model.addElement(text);
list.setSelectedValue(text, true);
}
});
list.addListSelectionListener(e -> {
output.setText(list.getSelectedValue());
});
del.addActionListener(e -> {
int id = list.getSelectedIndex();
if (id >= 0) {
model.remove(id);
list.setSelectedIndex(id - 1 > 0 ? id - 1 : 0);
}
});
}
@Override
public void addNotify() {
super.addNotify();
input.requestFocusInWindow();
}
public void createGui(int width, int height) {
setPreferredSize(new Dimension(width, height));
setLayout(null);
int off = width / 20;
int sizeWidth = width / 2 - 2 * off;
int sizeHeight = (height - 2 * off) / 7;
int xp = off;
int yp = off;
output.setFocusable(false);
add.setFocusable(false);
del.setFocusable(false);
list.setFocusable(false);
output.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
scroll.setBounds(xp, yp, sizeWidth, height - 2 * off);
xp += width / 2;
input.setBounds(xp, yp, sizeWidth, sizeHeight);
yp += 2 * sizeHeight;
add.setBounds(xp, yp, sizeWidth, sizeHeight);
yp += 2 * sizeHeight;
output.setBounds(xp, yp, sizeWidth, sizeHeight);
yp += 2 * sizeHeight;
del.setBounds(xp, yp, sizeWidth, sizeHeight);
add(input);
add(output);
add(add);
add(del);
add(scroll);
}
}