JLIST BACKGROUND SELECTION CHANGE
import javax.swing.*;
class First{
public static void main(String args[]){
Second gui = new Second();
gui.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
gui.setSize(300, 200);
gui.setVisible(true);
}
}
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
public class Second extends JFrame {
private JList list;
// Creating a visual array so the user can select
private static String[] colornames = {"black", "blue", "red", "white"};
// Creating a background array so java can understand
private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.white};
// Creating the constructor
public Second(){
// Setting title
super("Title");
// Setting layout
setLayout(new FlowLayout());
// Creating the list with the options of the colornames array
list = new JList(colornames);
// Setting the visible row count
list.setVisibleRowCount(4);
// Setting selection model, which lets us select a set amount of options ( in this case 1 )
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Adding a scrollpane with the options of our list
add(new JScrollPane(list));
// Creating a selection listener with an anonymous class
list.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// Accessing the content pane which is the visual on top of the background
// which is needed to access the Background
// & Then setting the background color based on the selected index
getContentPane().setBackground(colors[list.getSelectedIndex()]);
}
}
);
}
}