I have a list of choise. All i want to do, is when i click on a element - to show the string of that element. Suppose i click on "Pizza" element, then i should to get at console (with System.out.println()) the word -Pizza.
Any ideas or example will be very good!

import java.awt.*;
import java.awt.event.*;

class Fereastra extends Frame implements ItemListener{
	private Label label;
	private List colors;
	
	public Fereastra(String titlu){
		super(titlu);
		this.addWindowListener(new WindowAdapter (){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});
	
	setLayout(new GridLayout(2,1));
	label = new Label("Alegeti culoarea");
	label.setBackground(Color.red);
	
	colors = new List(3);
	colors.add("Rosu");
	colors.add("Verde");
	colors.add("Albastru");
	colors.select(3);
	
	add(label);
	add(colors);
	
	setSize(200,200);
	colors.addItemListener(this);
	}
	
	
	public void itemStateChanged(ItemEvent e){
	
	
		switch(colors.getSelectedIndex()){
			for(i=0; i<colors.getSize(); i++)
                        System.out.println(colors[i]); //When i click on element, should to print the String of element
	} 
}
}

public class TestList{
	public static void main(String args[]){
		Fereastra f = new Fereastra("Choice");
		f.show();
	}
}

colors.getSelectedItem() will give you the selected item in the list. Hold it in a String and print it out on the console using System.out.println()

But you have a GUI here and why do you wish to print the selected item to the console?

I work at a small project. To print the selected item to the console mean that i can get the String of elements.

I need the strings because in project, the elements of List will be some .txt files. I should get the name of .txt files and send it
that parameter.

FileReader fr = new FileReader(String_of_list_which_is_a_.txt_file)

colors.getSelectedItem() give me the selected INDEX in the list.
I hold in a String but the result is also "int".

int s = culori.getSelectedIndex(); 
String S = Integer.toString(s); //convert to string

Oops! I'm sorry!
Your are right Tuse!
I wrong getSelectedIndex with getSelectedItem!
Now, finally program is working!
Thank you!

System.out.println(colors.getText().toString());

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.