
I has done a JList that can change background color when i selected each of it, but if i want to change background image rather than background colors, how can i do it?
Please help!
my previous coding as below: import java.awt.*; import javax.swing.*; import javax.swing.event.*;
public class ListTest extends JFrame{ private JList colorList; private Container container;
private final String colorNames[]={"Black","Blue","Cyan","Dark Gray","Gray","Green","Light Gray","Magenta","Orange","Pink","Red","White","Yellow"};
private final Color colors[]={Color.BLACK,Color.BLUE,Color.CYAN,Color.DARK_GRAY,Color.GRAY,Color.GREEN,Color.LIGHT_GRAY,Color.MAGENTA,Color.ORANGE,Color.PINK,Color.RED,Color.WHITE,Color.YELLOW
};
public ListTest()
{
super("List Test");
container=getContentPane();
container.setLayout(new FlowLayout());
colorList= new JList(colorNames);
colorList.setVisibleRowCount(5);
colorList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
container.add(new JScrollPane(colorList));
colorList.addListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
container.setBackground(
colors[colorList.getSelectedIndex()]);
}
}
);
setSize(350,150);
setVisible(true);
}
public static void main(String args[])
{
ListTest application=new ListTest();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Java JList select Background Image
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
public class BackgroundImage1{
private BufferedImage image;
private JPanel panel = new JPanel(){
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, this);
}
}
};
public BackgroundImage1(){
panel.setLayout(null);
String files[]={"c:\\flower1.jpg","c:\\flower2.jpg","c:\\flower3.jpg","c:\\flower4.jpg"};
final JList list=new JList(files);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
String st = (String) list.getSelectedValue();
System.out.println(st);
try{
File file=new File(st);
image = ImageIO.read(file);
Dimension imageSize = new Dimension(image.getWidth(), image.getHeight());
panel.setPreferredSize(imageSize);
panel.repaint();
}
catch(Exception ex){}
}
}
});
list.setBounds(100,10,100,100);
panel.add(list);
}
public JPanel getPanel(){
return panel;
}
public static void main(String[] args){
JFrame frame = new JFrame("BackgroundImage ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BackgroundImage1().getPanel());
frame.setSize(300,150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.