OnJava8-Examples/gui/List.java

59 lines
1.6 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: gui/List.java
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*;
public class List extends JFrame {
private String[] flavors = {
"Chocolate", "Strawberry", "Vanilla Fudge Swirl",
"Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
"Praline Cream", "Mud Pie"
};
2015-05-05 11:20:13 -07:00
private int count = 0;
2015-05-06 12:09:38 -07:00
private DefaultListModel<String> lItems =
new DefaultListModel<>();
private JList<String> lst = new JList<>(lItems);
2015-04-20 15:36:01 -07:00
private JTextArea t =
new JTextArea(flavors.length, 20);
private JButton b = new JButton("Add Item");
2015-05-06 12:09:38 -07:00
private ActionListener bl = e -> {
2015-05-05 14:05:39 -07:00
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);
2015-04-20 15:36:01 -07:00
}
};
2015-05-06 12:09:38 -07:00
private ListSelectionListener ll = e -> {
if(e.getValueIsAdjusting()) return;
t.setText("");
for(Object item : lst.getSelectedValuesList())
t.append(item + "\n");
2015-05-05 14:05:39 -07:00
};
2015-04-20 15:36:01 -07:00
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);
}
} ///:~