Advertisement
makispaiktis

10. JList - Change background color

May 30th, 2022 (edited)
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.event.*;
  5.  
  6. public class Gui extends JFrame{
  7.  
  8.     // Variables
  9.     private JList list;
  10.     private static String[] colornames = {"black", "blue", "red", "white"};
  11.     private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.WHITE};
  12.  
  13.     // Constructor
  14.     public Gui(){
  15.  
  16.         super("JFrame's title");
  17.         setLayout(new FlowLayout());
  18.         list = new JList(colornames);
  19.         list.setVisibleRowCount(4);
  20.         list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);    // Select only 1 at a time
  21.         add(new JScrollPane(list));
  22.  
  23.         list.addListSelectionListener(
  24.                 new ListSelectionListener() {
  25.                     @Override
  26.                     public void valueChanged(ListSelectionEvent event) {
  27.                         // Access content pane ---> Set background
  28.                         getContentPane().setBackground(colors[list.getSelectedIndex()]);
  29.                     }
  30.                 }
  31.         );
  32.  
  33.     }
  34.  
  35.     // Main Function
  36.     public static void main(String[] args){
  37.         Gui gui = new Gui();
  38.         gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
  39.         gui.setSize(600, 600);
  40.         gui.setVisible(true);
  41.     }
  42.  
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement