Page 1 of 1

Swing Tutorial Part IV Learning Swing Rate Topic: ****- 1 Votes

#1 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Post icon  Posted 27 September 2009 - 01:43 PM

This chapter is about JList and JCombo box.

Remember, for all the Swing Methods and Constructors click here

Using a List

A list is a swing component that displays lists of objects within a box. We have total control over how the items in the list are displayed. To create a list and specify its items, we pass an array to the JList constructor. Then we call the setVisibleRowCount method to set the number of rows we want to be visible, thus adding the list to the scroll pane, then add the scroll pane to a panel so that we can later add to the frame.

Here we create an array of Strings

String[] months = {"Jan.", "Feb.", "March", "April", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec"};

Now, adding the Strings to the list

list = new JList(months);

Then set 5 rows to be visible on the list

list.setVisibleRowCount(5)

Hence, add the list to the scroll pane

JScrollPane scroll = new JScrollPane(list);

Finally, add the scroll pane to a panel

JPanle panel = new JPanel();

Now, Lets see a more detail and complete example with outputs

/*
	The program demonstrate the use of a list

*
*/

import javax.swing.*;

public class List extends JFrame
{
	JPanel panel;
	JScrollPane scroll;
	JList list;
	JLabel msg;

	public List()
	{
		// Sets the title of the window

		setTitle("JList Window");

		// Sets the size of the window

		setSize(300, 400);

		// Sets the action when the window close

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Sets the label of the window

		msg = new JLabel("Here are the months");

		// Create a String of array

		String[] months = {"Jan.", "Feb.", "March", "April", "May", "June",
									"July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."};

		// Adds the array of string into the list

		list = new JList(months);

		// Sets the visibility of the list

		list.setVisibleRowCount(5);

		// Adds the list to a scroll pane

		JScrollPane scroll = new JScrollPane(list);

		// Adds the scroll pane and the label to a panel

		panel = new JPanel();
		panel.add(msg);
		panel.add(scroll);

		// Adds the panel to a content pane

		add(panel);

		// Set the window to be visible

		setVisible(true);

	}

	public static void main(String[] args)
	{
		new List();

	}
}



Posted Image

The above program only allows us to scroll down and up to see the list. JList also able us to select from the list then display what we've selected to the screen. Lets see a more expanded version of months, and this time we are allow to select which ever months we want from the list.

/*
	The program demonstrate the use of a list
	In addition we are able to select from the list

*
*/

import javax.swing.*;
import java.awt.event.*;

public class SelectList extends JFrame
{
	JPanel panel;
	JScrollPane scroll;
	JList list;
	JLabel msg;
	JButton ok;

	public SelectList()
	{
		// Sets the title of the window

		setTitle("JList Window");

		// Sets the size of the window

		setSize(300, 400);

		// Sets the action when the window close

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Sets the label of the window

		msg = new JLabel("Here are the months");

		// Creates a OK button

		ok = new JButton("OK");

		// Create a String of array

		String[] months = {"Jan.", "Feb.", "March", "April", "May", "June",
									"July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."};

		// Adds the array of string into the list

		list = new JList(months);

		// Sets the visibility of the list

		list.setVisibleRowCount(5);

		// Adds the list to a scroll pane

		JScrollPane scroll = new JScrollPane(list);

		// Adds the scroll pane, the label and OK button to a panel

		panel = new JPanel();
		panel.add(msg);
		panel.add(scroll);
		panel.add(ok);

		// Adds the panel to a content pane

		add(panel);

		// Creates a single selection mode

		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		// Creates an event listener

		ok.addActionListener(new okButtonListener());

		// Set the window to be visible

		setVisible(true);

	}

	public class okButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if(e.getSource()==ok)
			{
				String select = (String)list.getSelectedValue();

				JOptionPane.showMessageDialog(null, "You have selected " + select );

			}
		}
	}

	public static void main(String[] args)
	{
		new SelectList();

	}
}



Posted Image

The above example, the only things different from the previous example is the button and we added a new method from JList, which is setSlectionMode(int mode). Inside the button listener we added String select = (String) list.getSelectedValue() basically, it gets a single value from the list then assign it to select. The getSelectedValue method is in the JList class. What if we want to select more than one from the list, luckily we have another method in JList that allows us to select more than one from the list. I will use the same example above just so we can easily tell the difference between just a JList, a single selectable JList, and a more than one selectable JList.

/*
	The program demonstrate the use of a list
	In addition we are able to select more than one from the list

*
*/

import javax.swing.*;
import java.awt.event.*;

public class SelectLists extends JFrame
{

	JPanel panel;
	JScrollPane scroll;
	JList list;
	JLabel msg;
	JButton ok;

	public SelectLists()
	{
		// Sets the title of the window

		setTitle("JList Window");

		// Sets the size of the window

		setSize(300, 400);

		// Sets the action when the window close

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Sets the label of the window

		msg = new JLabel("Here are the months");

		// Creates a OK button

		ok = new JButton("OK");

		// Create a String of array

		String[] months = {"Jan.", "Feb.", "March", "April", "May", "June",
									"July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."};

		// Adds the array of string into the list

		list = new JList(months);

		// Sets the visibility of the list

		list.setVisibleRowCount(5);

		// Adds the list to a scroll pane

		JScrollPane scroll = new JScrollPane(list);

		// Adds the scroll pane, the label and OK button to a panel

		panel = new JPanel();
		panel.add(msg);
		panel.add(scroll);
		panel.add(ok);

		// Adds the panel to a content pane

		add(panel);

		// Creates a single selection mode

		list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		// Creates an event listener

		ok.addActionListener(new okButtonListener());

		// Set the window to be visible

		setVisible(true);

	}

	public class okButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if(e.getSource()==ok)
			{
				Object[] select = list.getSelectedValues();

				String msg = "You have selected the following months: \n";

				// Using a loop to store the selection in the select array

				for(Object selection : select )
				{
					msg += (String)selection + "\n";
				}

				JOptionPane.showMessageDialog(null, msg);

				// Clears all the selection
   
				list.clearSelection();

			}
		}
	}

	public static void main(String[] args)
	{
		new SelectLists();

	}
}



Posted Image

The only difference from this example is the selectionMode has changed to MULTIPLE_INTERVAL_SELECTION, and we used a different getSelected method, in addition to that we used a loop to loop out the array. It is not much a different from the previous 3 examples besides the methods are different


JComboBox

A combo box is a combination of a text field and a drop-down list where the user can choose a value. It's very similar to a JList.

Creating a JComboBox

JComboBox jcombo = new JComboBox();

Adding items to the combo Box

jcombo.addItem("Jan.");
jcombo.addItem("Feb.");
jcombo.addItem("March");

Alternative way of adding to the combo box using array

String[] month = {"Jan.", "Feb.", "March"};

JComboBox jcombo = new JComboBox(month);

/*
	This is a simple JCombo Box GUI

*
*/

import javax.swing.*;
import java.awt.event.*;

public class JCombo_Box extends JFrame
{
	// Sets to private so only the same class can access these members

	private JComboBox jcombo;
	private JPanel panel;
	private JButton ok;

	public JCombo_Box()
	{
		// Sets the title of the window

		setTitle("JCombo Box Window");

		// Sets the size of the window

		setSize(300, 200);

		// Sets the appearance location of the window to the middle of the screen

		setLocationRelativeTo(null);

		// Sets the action when a window is close

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Creates a JComob Box

		jcombo = new JComboBox();

		// Adds the item to the JCombo Box

		jcombo.addItem("Jan.");
		jcombo.addItem("Feb.");
		jcombo.addItem("March");
		jcombo.addItem("April");
		jcombo.addItem("May");
		jcombo.addItem("June");
		jcombo.addItem("July");
		jcombo.addItem("Aug.");
		jcombo.addItem("Sept.");
		jcombo.addItem("Oct.");
		jcombo.addItem("Nov.");
		jcombo.addItem("Dec.");

		// Create a panel

		panel = new JPanel();

		// Creates a OK button

		ok = new JButton("OK");

		// Creates a event listener to handle the event

		ok.addActionListener(new okButtonListener());

		// Adds the JCombo Box and ok button to the panel

		panel.add(jcombo);
		panel.add(ok);

		// Adds the window to the content pane

		add(panel);

		// Sets the window to be true

		setVisible(true);

	}

		/*
			JCombo Box returns an object, so when we get the selection
			We must specify what is the type of the object
			In this case the type is a String

		*
		*/

	private class okButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			if(e.getSource()==ok)
			{
				String select = (String)jcombo.getSelectedItem();

				JOptionPane.showMessageDialog(null, "You have selected " + select);

			}
		}
	}

	public static void main(String[] args)
	{
		new JCombo_Box();

	}
}



Posted Image

Is This A Good Question/Topic? 2
  • +

Replies To: Swing Tutorial Part IV

#2 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 04 October 2009 - 10:10 AM

Please!! Do leave some feedbacks so i know what to improve...

is it confusing, not clear enough, needs more examples and so on..

open for any suggestions...
Was This Post Helpful? 2
  • +
  • -

#3 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Posted 19 October 2012 - 11:04 AM

String select = (String)list.getSelectedValue();


why code above can work..? as I know if you want to access another class variable's value, need a reference or accessor method..? and list is in SelectList class..

Would you mind explain to me? thanks.
Was This Post Helpful? 0
  • +
  • -

#4 jinnyishere  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 46
  • View blog
  • Posts: 127
  • Joined: 06-July 09

Posted 22 March 2013 - 02:04 AM

View PostJohn-acme, on 19 October 2012 - 11:04 AM, said:

String select = (String)list.getSelectedValue();


why code above can work..? as I know if you want to access another class variable's value, need a reference or accessor method..? and list is in SelectList class..

Would you mind explain to me? thanks.


Hi, I know it's been a year but better late than never.

If you look at the following:

//Here we create an array of Strings

String[] months = {"Jan.", "Feb.", "March", "April", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec"};

//Now, adding the Strings to the list
list = new JList(months);


We have just created a JList, name " list ".

Now in order to get the selected value from the list, we use the " getSelectedValue() " method from JList. That method returns an object, so we have to cast it into a String.

"Note: I didn't create the method getSelectedValue(), it's already defined in the JList class"

Hope that helps..

~Jay
Was This Post Helpful? 2
  • +
  • -

#5 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Posted 09 April 2013 - 02:40 AM

Thanks for the explanation.. yeah better late than never.. ^^

Yes I can understand your explanation, (even your answer didn't fully answer my question.. sorry) and also now (after a long time) I found out the answer of my question (you're using inner class, that why the "String select" in okbuttonlistener class can access JList in SelectList class.. hehe )

Thanks anyway ..
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,475
  • Joined: 27-December 08

Posted 09 April 2013 - 09:37 PM

To note as well- as of Java 7, JList is generic. So there is no need to cast the elements.
Was This Post Helpful? 0
  • +
  • -

#7 John-acme  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 65
  • Joined: 08-February 11

Posted 15 April 2013 - 11:52 AM

@macosxnerd101 : would you mind to explain more about the "no need of casting" in Java 7?

This post has been edited by John-acme: 15 April 2013 - 11:53 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1