How to Add Images to a JList In Java Netbeans
In this Java Tutorial we will see How To Create a JList With Images Inside It In Java Using Netbeans.
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
Project Source Code:
package new_tutorials;
import java.awt.Component;
import java.util.Vector;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
/**
*
* @author 1BestCsharp
*/
public class JListWithImagesFrame extends JFrame{
public JListWithImagesFrame(){
setTitle("JList With Images Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setLocationRelativeTo(null);
initializeUI();
}
// Method to set up the UI components
private void initializeUI(){
// Create a Vector to store ListItem objects
Vector<ListItem> listItems = new Vector<>();
listItems.add(new ListItem("Manager",loadImage("manager.png")));
listItems.add(new ListItem("Developer",loadImage("developer.png")));
listItems.add(new ListItem("Designer",loadImage("designer.png")));
listItems.add(new ListItem("Analyst",loadImage("analyst.png")));
// Create a JList with ListItem objects and set a custom cell renderer
JList<ListItem> list = new JList<>(listItems);
list.setCellRenderer(new ImageListCellRenderer());
// Add the JList to a JScrollPane and add the scroll pane to the content pane
JScrollPane scrollPane = new JScrollPane(list);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
JListWithImagesFrame frame = new JListWithImagesFrame();
frame.setVisible(true);
}
// Custom cell renderer for displaying images and text in the JList
private class ImageListCellRenderer extends DefaultListCellRenderer{
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean hasFocus){
super.getListCellRendererComponent(list, value, index, isSelected, hasFocus);
// Check if the value is an instance of ListItem
if(value instanceof ListItem item){
// Set the icon and text for the cell
setIcon(item.getImageIcon());
setText(item.getText());
}
return this;
}
}
// Method to load an image from the "images" package
private static ImageIcon loadImage(String imageName){
// Load image from the "images" package
String imagePath = "images/" + imageName;
return new ImageIcon(JListWithImagesFrame.class.getResource(imagePath));
}
}
// Create a class to represent an item in the JList with a name and an associated image
class ListItem{
private final String text;
private final ImageIcon image;
// constructor
public ListItem(String txt, ImageIcon img){
this.text = txt;
this.image = img;
}
// Getters
public String getText(){ return text; }
public ImageIcon getImageIcon(){ return image; }
}
The Final Result:
More Java Projects:
Download Projects Source Code