Hi everyone,
I want to create a simple GUI that prompts user to browse for a text file, read in that file and display them in the GUI as a list. Then it should allow user to select from that list. Once an element is selected, there should be a little window (just like a textfield) to pop up asking user to put in a digit number. When they did that, and hit enter the element they selected from the list should be printed to the screen. Also, I want to get the values (the element selected from the list and the digit number keyed in by user) be returned in two separate method. How can I do that? Thanks a lot in advance.
Here is the code I had so far. For now, it allows I to browse the file, read in that file and display the data as a list in the GUI. When I click an element in that list, it will get print out to the screen.
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class SampleGUI extends Frame implements ItemListener{
private Label label;
private static List alist;
public static void main(String args[]){
SampleGUI sg = new SampleGUI();
}
public SampleGUI(){
super("Sample GUI");
this.addWindowListener(new WindowAdapter (){
public void windowClosing(WindowEvent e){
System.exit(0);
} } );
setLayout(new GridLayout(1,1));
label = new Label("Select what you want");
label.setBackground(Color.lightGray);
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt") || f.isDirectory();
}
public String getDescription() {
return "TXT Files";
}});
int r = chooser.showDialog(new JFrame(),"Select .TXT File");
if (r == JFileChooser.APPROVE_OPTION) {
chooser.getSelectedFile().getName();
}
if(r == JFileChooser.CANCEL_OPTION) System.exit(0);
String [] str_array;
/*
Code to read in data from the input file and add to an array "str_array".
*/
alist = new List(str_array.length);
for(int i = 0; i < str_array.length;i++)
{
alist.add(str_array[i].toString());
}
add(label);
add(alist);
setSize(600,200);
setVisible(true);
alist.addItemListener(this);
}
public void itemStateChanged(ItemEvent e){
for(int i = 0; i < alist.getItemCount(); i++)
{
if(alist.getSelectedIndex() == i)
System.out.println(alist.getItem(i));
}
}
}