Как у випадающый списак закынуть картинку и натпись - Java
Формулировка задачи:
как у випадающый списак (JComboBox) закынуть картинку и натпись? вид неважно , главно чтоби закинуть. Я панемаю что, можна, закинуть панель з лейболом и иконкой. но наверно есть и другой способ?P.S извините за ошипки плохо знаю руский
Решение задачи: «Как у випадающый списак закынуть картинку и натпись»
textual
Листинг программы
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
/**
*
* @author ramil
*/
public class JImageComboBoxFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JImageComboBoxFrame().setVisible(true);
}
});
}
public JImageComboBoxFrame() {
super("JComboBox with images");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String imagesPath = "/usr/share/icons/gnome/16x16/devices";
ArrayList<ImageHolder> list = new ArrayList<ImageHolder>();
for (File file : new File(imagesPath).listFiles()) {
list.add(new ImageHolder(
file.getName(),
new ImageIcon(file.getAbsolutePath())));
}
JComboBox comboBox = new JComboBox(list.toArray());
comboBox.setRenderer(new ImageHolderRenderer());
add(comboBox);
pack();
setLocationRelativeTo(null);
}
public static class ImageHolder {
public ImageHolder(String description, Icon image) {
this.description = description;
this.image = image;
}
public final String description;
public final Icon image;
}
public static class ImageHolderRenderer
extends JLabel
implements ListCellRenderer
{
public ImageHolderRenderer() {
setOpaque(true); // что-бы можно было отображать выделеные элементы
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
ImageHolder imageHolder = (ImageHolder) value;
setIcon(imageHolder.image);
setText(imageHolder.description);
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
}