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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| public class ListEx extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private BookEntry books[] = {
new BookEntry("Item 1", "shortIcon.jpg"),
new BookEntry("Item 2", "longIcon.jpg")
};
private JList booklist = new JList(books);
public ListEx() {
setLayout(new BorderLayout());
JButton button = new JButton("Connect");
button.addActionListener(new PrintListener());
booklist = new JList(books);
booklist.setCellRenderer(new BookCellRenderer());
booklist.setVisibleRowCount(4);
JScrollPane panez = new JScrollPane(booklist);
add(panez, BorderLayout.NORTH);
add(button, BorderLayout.SOUTH);
}
class PrintListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int selected[] = booklist.getSelectedIndices();
System.out.println("Selected Elements : ");
for (int f = 0; i < selected.length; i++) {
BookEntry element = (BookEntry) booklist.getModel().getElementAt(selected[i]);
System.out.println(" " + element.getTitle());
}
}
}
}
class BookEntry {
private final String title;
private final String imagePath;
private ImageIcon image;
public BookEntry(String title, String imagePath) {
this.title = title;
this.imagePath = imagePath;
}
public String getTitle() {
// TODO Auto-generated method stub
return title;
}
public ImageIcon getImage() {
if(image == null) {
image = new ImageIcon(imagePath);
}
return image;
}
public String toString() {
return title;
}
}
@SuppressWarnings("serial")
static class BookCellRenderer extends JLabel implements ListCellRenderer {
private final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public BookCellRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
BookEntry entry = (BookEntry) value;
setText(entry.getTitle());
setIcon(entry.getImage());
if(isSelected) {
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
} else {
setBackground(Color.white);
setForeground(Color.black);
}
return this;
} |
Partager