View RSS Feed

fatabass

JList Example

Rating: 1 votes, 1.00 average.
by , 12-27-2011 at 11:17 PM (4064 Views)
Java Code:
package myPackage;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListFrame extends JFrame
{
	JList myJList;
	String[] colorrs;
	JLabel colorSelected;
	
	public ListFrame()
	{
		super("This is a List Frame");
		this.setLayout(new FlowLayout());
		
		colorrs = new String[6];
		
		colorrs[0] = "Red";
		colorrs[1] = "Blue";
		colorrs[2] = "Green";
		colorrs[3] = "Black";
		colorrs[4] = "White";
		colorrs[5] = "Purple";

		myJList = new JList();
		myJList.setSelectionMode(
                ListSelectionModel.SINGLE_SELECTION);
		myJList.setListData( colorrs );
		myJList.setVisibleRowCount(4);
		myJList.addListSelectionListener(new ListenerClass());
		
		JScrollPane scrollPane = new JScrollPane(myJList);
		this.add(scrollPane);
		
		colorSelected = new JLabel("Please Select a Color!");
		this.add(colorSelected);
		
	}// end Constructor

	class ListenerClass implements ListSelectionListener
	{
		public void valueChanged(ListSelectionEvent event) 
		{
			String selected = 
(String) myJList.getSelectedValue();
			colorSelected.setText
("You have selected: " + selected);
		}//end method valueChanged
	
	}//end class ListenerClass

}//end class ListFrame

Java Code:
package myPackage;

import javax.swing.JFrame;

public class ListFrameTest 
{
	public static void main(String[] args) 
	{
		ListFrame myFrame = new ListFrame();
		myFrame.setSize(400,250);
		myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myFrame.setVisible(true);
	}
}
Name:  01.png
Views: 1381
Size:  6.2 KBName:  02.png
Views: 1565
Size:  7.0 KB

Submit "JList Example" to Facebook Submit "JList Example" to Digg Submit "JList Example" to del.icio.us Submit "JList Example" to StumbleUpon Submit "JList Example" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments

  1. fatabass's Avatar
    • |
    • permalink
    Please feel free to comment & ask questions.
    Thanks.
  2. utkarsh 1's Avatar
    • |
    • permalink
    hi
    i want to do same thing but i want to display a image when i choose name from the list what change should make in the code
  3. fatabass's Avatar
    • |
    • permalink
    colorSelected = new JLabel(new ImageIcon("c://anImage.jpg"));