2015-09-07 11:44:36 -06:00
|
|
|
// ui/List.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import javax.swing.*;
|
|
|
|
import javax.swing.border.*;
|
|
|
|
import javax.swing.event.*;
|
|
|
|
import java.awt.*;
|
|
|
|
import java.awt.event.*;
|
2015-11-11 20:20:04 -08:00
|
|
|
import static onjava.SwingConsole.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
public class List extends JFrame {
|
|
|
|
private String[] flavors = {
|
|
|
|
"Chocolate", "Strawberry", "Vanilla Fudge Swirl",
|
|
|
|
"Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
|
|
|
|
"Praline Cream", "Mud Pie"
|
|
|
|
};
|
|
|
|
private int count = 0;
|
|
|
|
private DefaultListModel<String> lItems =
|
|
|
|
new DefaultListModel<>();
|
|
|
|
private JList<String> lst = new JList<>(lItems);
|
|
|
|
private JTextArea t =
|
|
|
|
new JTextArea(flavors.length, 20);
|
|
|
|
private JButton b = new JButton("Add Item");
|
|
|
|
private ActionListener bl = e -> {
|
|
|
|
if(count < flavors.length) {
|
|
|
|
lItems.add(0, flavors[count++]);
|
|
|
|
} else {
|
|
|
|
// Disable, since there are no more
|
|
|
|
// flavors left to be added to the List
|
|
|
|
b.setEnabled(false);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
private ListSelectionListener ll = e -> {
|
|
|
|
if(e.getValueIsAdjusting()) return;
|
|
|
|
t.setText("");
|
|
|
|
for(Object item : lst.getSelectedValuesList())
|
|
|
|
t.append(item + "\n");
|
|
|
|
};
|
|
|
|
public List() {
|
|
|
|
t.setEditable(false);
|
|
|
|
setLayout(new FlowLayout());
|
|
|
|
// Create Borders for components:
|
|
|
|
Border brd = BorderFactory.createMatteBorder(
|
|
|
|
1, 1, 2, 2, Color.BLACK);
|
|
|
|
lst.setBorder(brd);
|
|
|
|
t.setBorder(brd);
|
|
|
|
// Add the first four items to the List
|
|
|
|
for(int i = 0; i < 4; i++)
|
|
|
|
lItems.addElement(flavors[count++]);
|
|
|
|
add(t);
|
|
|
|
add(lst);
|
|
|
|
add(b);
|
|
|
|
// Register event listeners
|
|
|
|
lst.addListSelectionListener(ll);
|
|
|
|
b.addActionListener(bl);
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
run(new List(), 250, 375);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|