Advertisement
thenewboston

Java Programming Tutorial - 70, 71 - JList

Aug 22nd, 2014
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. import java.awt.FlowLayout;
  2. import java.awt.Color;
  3. import javax.swing.JList;
  4. import javax.swing.JFrame;
  5. import javax.swing.JScrollPane;
  6. import javax.swing.ListSelectionModel;
  7. import javax.swing.event.ListSelectionListener;
  8. import javax.swing.event.ListSelectionEvent;
  9.  
  10. class ListGUI extends JFrame {
  11.    private JList list;
  12.    private String colorNames[ ] = {"black", "blue", "red", "green"};
  13.    private Color colors[ ] = {Color.BLACK, Color.BLUE, Color.RED, Color.GREEN};
  14.    
  15.    public static void main(String args[ ]) {
  16.       ListGUI gui = new ListGUI();
  17.       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  18.       gui.setSize(300, 200);
  19.       gui.setVisible(true);
  20.    }
  21.      
  22.    ListGUI() {
  23.       super("background changer");
  24.       setLayout(new FlowLayout());
  25.      
  26.       list = new JList(colorNames);
  27.       list.setVisibleRowCount(colorNames.length);
  28.       list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  29.       add(new JScrollPane(list));
  30.       getContentPane().setBackground(colors[0]);
  31.      
  32.       list.addListSelectionListener(
  33.          new ListSelectionListener() {
  34.             public void valueChanged(ListSelectionEvent event) {
  35.                getContentPane().setBackground(colors[list.getSelectedIndex()]);  
  36.             }
  37.          }
  38.       );
  39.    }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement