Friday, 15 August 2014

JAVA - JList

An example of JAVA's SWING  JList  .

To display the selected color from list and change the background
I choosed black, coz its my favourite ... lol 

Main class -

import javax.swing.JFrame;


public class Main  extends JFrame{
public static void main(String args[]){
GUI go = new GUI();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(300,200);
go.setVisible(true);
}


}


JList functionality class - 


import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class GUI extends JFrame {
private JList list;
private static String[] colorNames = {"red", "blue" , "black", "red", "blue" , "black","red", "blue" , "black"};
private static  Color[] colors= {Color.RED ,Color.BLUE ,Color.BLACK, Color.RED ,Color.BLUE ,Color.BLACK ,Color.RED ,Color.BLUE ,Color.BLACK};

//constructor
public GUI(){
super("Title");
setLayout(new FlowLayout());
//initialise  list with color names to select
list = new JList(colorNames);
//set visible row count 
list.setVisibleRowCount(9);
//set the list selection mode
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//add the list view 
//JScrollPane  displays the contents of the specified component, 
//where both horizontal and vertical scrollbars
//appear whenever the component's contents are larger than the view
add(new JScrollPane(list));
//add  a listener to the list, to be notified each time a change 
//to the selection occurs; the preferred way of listening for 
//selection state changes.
list.addListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
//set backgroud via content pane
// there are three layers of a view - background ,glass , content 
getContentPane().setBackground(colors[list.getSelectedIndex()]);
}
}
);
}
}


No comments:

Post a Comment