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));
        }

    }

}

Can you edit your post and wrap the code in code tags? Use the [code] icon above the input box.
Unformatted code is hard to read and understand.

Can you edit your post and wrap the code in code tags? Use the [CODE] icon above the input box.
Unformatted code is hard to read and understand.

Hi NormR1,

Sorry, I do not know the code should be put in code tags.

I edited it again. Hope this is fine this time :-):-)

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));
    }
  }
} 

The code still is unformatted. It should be indented 3-4 spaces for every nesting level within a pair of {}s. Your code has no indentation which makes it hard to read and understand. Also you should put each } on its own line. No } should be directly underneath another }

The code still is unformatted. It should be indented 3-4 spaces for every nesting level within a pair of {}s. Your code has no indentation which makes it hard to read and understand. Also you should put each } on its own line. No } should be directly underneath another }

Code edited. Hope this is formatted this time.

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));
              }
         }
    }

I get this error when I try to compile the code;

SampleGUI.java:62: variable str_array might not have been initialized
      alist = new List(str_array.length);
                       ^

You need to give a value to the str_array before executing this line.

I get this error when I try to compile the code;

SampleGUI.java:62: variable str_array might not have been initialized
      alist = new List(str_array.length);
                       ^

You need to give a value to the str_array before executing this line.

Yes I knew that I need to give it a value. The reason I put it like that since as I said the program will read in the input file and put data into that String array then it will have some values in it.

Ok, let's initialize that array like this:

String [] str_array = new String [] {"a","b","c","d","e"};

I have tested it and it worked. Thanks.

Where is the code to read in the file?

If you have specific questions you should ask them.

Where is the code to read in the file?

If you have specific questions you should ask them.

I do not think I need to put it in here since that part already worked fine for me. The only issue is that I do not know how to do the TextField that prompts the user to key in a digit number. As I said, what I want is that when the user click an element in the list, an box should pop up and let user key in a digit number and when they hit enter the that box should close up. I also want to have the digit number they key in and the element they selected in the list be returned by two separate methods but I am not sure how to do that. Thanks.

how to do the TextField that prompts the user to key in a digit number

TextFields don't prompt users. They receive input from users.

How do you test the program? Can the file chooser be removed for testing?
Have a program that shows the list and allows the user to select an item in the list and then do what you want next.

I'm done for tonight.
See you tomorrow.

TextFields don't prompt users. They receive input from users.

How do you test the program? Can the file chooser be removed for testing?
Have a program that shows the list and allows the user to select an item in the list and then do what you want next.

I'm done for tonight.
See you tomorrow.

Thanks NormR1. I compiled and run it using JDeveloper. With or without the file chooser it worked fine. The program did display the elements in the list and when an element in that list clicked, it is printed to the screen just fine. Now I just want a TextField pop up and let user key in and digit number...etc just like what I have described in my post above. Anyone has any sample code? Thanks a lot in advance.

Would a JOptionPane method do what you want: Display a message and ask the user for input.

Would a JOptionPane method do what you want: Display a message and ask the user for input.

Hi NormR1,

How are you today? Thank you for get back to this and helping me.

I just looked at the java document for it. I think that's what I need. As I am new to java GUI stuffs so I am not sure how to do it now. I will try to come up with some code and we may continue going from there.

I have a couple questions:

1- How would I make this method to return a String, which is the element in the list that user selected. If you compile and run my code it will show a list of letters: a, b, c, d, e. When an character is clicked it will get printed to the screen. But I also want to get this String returned in a separate method. How would I do that?

public void itemStateChanged(ItemEvent e){
     for(int i = 0; i < alist.getItemCount(); i++)
     {
          if(alist.getSelectedIndex() == i)
          System.out.println(alist.getItem(i));
     }

2- I need the file chooser part to tun first. It will let user browse for an input file. When they choose it and hit enter or click OK or Open, it will bring up an little box to display a message and ask user to input an digit number. When they did that and close the window, here come the part to read in the input file they chose and display the data in the list as you can see if you run my code. I also want to get the digit number keyed in by user to return in a separate method. How could I do all of this? I think I could do each of them but do not know how to tie them all together.

Thanks.

want to get this String returned in a separate method.

You can't. The method that gets the selected String is a listener. Listener methods are void - they do not return anything. The listener can save the selected value in a class variable where other methods can access it. You could have a method return that saved value.

. I also want to get the digit number keyed in by user to return in a separate method

Not sure where/how you expect to call this method. If you save the number that was entered in a class variable, you could have a method that returns that value.

The problem could be that the code/methods that call those methods would need to know if the values were available yet since they both require that the user enter them.
You should think through the timing of when the data is entered and when you want to get the values that were entered.

You can't. The method that gets the selected String is a listener. Listener methods are void - they do not return anything. The listener can save the selected value in a class variable where other methods can access it. You could have a method return that saved value.
Not sure where/how you expect to call this method. If you save the number that was entered in a class variable, you could have a method that returns that value.

The problem could be that the code/methods that call those methods would need to know if the values were available yet since they both require that the user enter them.
You should think through the timing of when the data is entered and when you want to get the values that were entered.

Thanks a lot. That really helps me.

1- I looked and noticed the ItemListener interface does not have any class variable so how can I have my GUI do the same thing and still can get that string they choose (by clicking an element in the list) saved as a class variable?

2- I think I will save both of them (the number and the string as class variables and have two methods to return them.

The listener could be a method in the class so it should not have a problem saving to a class variable.

The listener could be a method in the class so it should not have a problem saving to a class variable.

NormR1,

I edited the code adding those methods that will save the selected String and the number put in by user to the class variables. I commented out the file chooser part. When I run it, the input number was set correctly, but the String variable was always null. What am I missing here ? Thanks.

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class SampleGUI extends Frame implements ItemListener{
    
     
    private Label label;
    private static List alist;
    private String astring;
    private String anumber;


    public static void main(String args[]){
        SampleGUI sg = new SampleGUI();
        System.out.println("class variable astring: " + sg.getString());
        System.out.println("class variable anumber: " + sg.getNumber());
        
    }
     
    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);
*/

    JFrame frame = new JFrame();
    Object result = JOptionPane.showInputDialog(frame, "Enter a number:");
    System.out.println("User put in: " + result);
    setNumber(result.toString());
    
    
    /*
     Code to read in data from the input file and add to an String array "str_array".
     Since this part already worked fine for me, so I will not put it here and just
     assume that the String array "str_array" was initialized like bellow.
     */
     
    String [] str_array = new String[] {"a","b","c","d","e"};
     
    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));
                setString (alist.getItem(i));
        } 
    }
    
    public String getString() {
        return astring;
    }
    
    public String getNumber (){
        return anumber;                
    }
    
    
    public void setNumber(String anumber) {
        this.anumber = anumber ;
    }
    
    
    public void setString (String astring){
        this.astring = astring;                
    }  
    
}

the String variable was always null.

You don't give the name of the variable that is null and where in the code that you are getting the null value.

Earlier I said:
You should think through the timing of when the data is entered and when you want to get the values that were entered.

Are you trying to get a value BEFORE it is saved?

You don't give the name of the variable that is null and where in the code that you are getting the null value.

Earlier I said:
You should think through the timing of when the data is entered and when you want to get the values that were entered.

Are you trying to get a value BEFORE it is saved?

Ok, I will think about what you meant. Of cause, I want to get a value that is selected by user (hence I think it should be AFTER it is saved) but I am not sure how to do it?

I've to go. I will see you when I get home. Thanks a lot for your help.

it should be AFTER it is saved

With a GUI app the logic is different from a console where you prompt and read input.
With a GUI app you get the input when the user does some action that causes an event.

When that event happens, you can get the String the user entered and use it as you want.

With a GUI app the logic is different from a console where you prompt and read input.
With a GUI app you get the input when the user does some action that causes an event.

When that event happens, you can get the String the user entered and use it as you want.

I would think the action is that when the user click that element in the list but not sure that will cause an event. As you can see in my code, I have two class variables that I want them set: astring and anumber. The anumber variable was set correctly when the user put in a number. Meanwhile, the astring variable was not set to what the user chose from that list. The code to set that astring variable is inside the itemStateChanged(ItemEvent e) method:

public void itemStateChanged(ItemEvent e){
     for(int i = 0; i < alist.getItemCount(); i++)
     {
          if(alist.getSelectedIndex() == i)
          System.out.println(alist.getItem(i));
          setString (alist.getItem(i));
     }
}

Why I can print out that string to the screen but it will not get set although I called the setString (alist.getItem(i)). It always get a null value. What did I do wrong here? Thanks.

Let me repeat:
You should think through the timing of when the data is entered or selected and when you want to get the values that were entered.

Add printlns next to all the statements of interest here so that you can see when they are executed.

I would think the action is that when the user click that element in the list but not sure that will cause an event.

public void itemStateChanged(ItemEvent e){

The ItemEvent object passed to the listener method above is what I mean by an event.

Let me repeat:
You should think through the timing of when the data is entered or selected and when you want to get the values that were entered.

Add printlns next to all the statements of interest here so that you can see when they are executed.

public void itemStateChanged(ItemEvent e){

The ItemEvent object passed to the listener method above is what I mean by an event.

Thanks a lot NormR1. I think I am almost there. I will do that next week. Good night and have a good weekend.

Let me repeat:
You should think through the timing of when the data is entered or selected and when you want to get the values that were entered.

Add printlns next to all the statements of interest here so that you can see when they are executed.

public void itemStateChanged(ItemEvent e){

The ItemEvent object passed to the listener method above is what I mean by an event.

NormR1,

How are you today?

I thought that I will get it done right but unfortunately I am not there yet. I edited my code (inside the itemStateChanged(ItemEvent e) method) to set the class variables "astring" to what the user selected. I also add print statements printing out that class variable. When I run this program it first bring up a box asking the user for a number. When they entered it and hit OK, it will pop up my GUI with the list of elements in the String array. At this point, I noticed that the print statements inside my main() method have already executed and printed out the value of the class variable "astring" and "anumber". The "anumber" was set correctly to what the user keyed in, but the "astring" is NULL. This is right because those printing statements was executed before an element in that list selected. I then click each item in that list to check if it the "astring" variable was set correctly and it turned out that it was as the printing statement shown that on the screen. The problem is that I want those two variables to be set to what user entered and selected and they will be available to other classes, methods to use them. So how can I handle this? As I read your previous message, I've got what you meant by that but I really stuck and not sure how to achieve this. Please help. Thanks a lot.

"The problem could be that the code/methods that call those methods would need to know if the values were available yet since they both require that the user enter them.
You should think through the timing of when the data is entered and when you want to get the values that were entered."

Here is the revised code:

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class SampleGUI extends Frame implements ItemListener{
    
     
    private Label label;
    private static List alist;
    public String astring;
    public String anumber;


    public static void main(String args[]){
        SampleGUI sg = new SampleGUI();
        System.out.println("class variable astring: " + sg.getString());
        System.out.println("class variable anumber: " + sg.getNumber());
        
    }
     
    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);
*/

    JFrame frame = new JFrame();
    Object result = JOptionPane.showInputDialog(frame, "Enter a number:");
    System.out.println("User put in: " + result);
    setNumber(result.toString());
    
    
    /*
     Code to read in data from the input file and add to an String array "str_array".
     Since this part already worked fine for me, so I will not put it here and just
     assume that the String array "str_array" was initialized like bellow.
     */
     
    String [] str_array = new String[] {"a","b","c","d","e"};
     
    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("item selected: " + alist.getItem(i));
                int a = e.SELECTED;           
                int b = e.getStateChange();

                if(a == b)
                {
                    setString (alist.getItem(i));
                    System.out.println("class variable astring: " + astring);
                }
            }
        } 
    }
    
    public String getString() {
        return astring;
    }
    
    public String getNumber (){
        return anumber;                
    }
    
    
    public void setNumber(String anumber) {
        this.anumber = anumber ;
    }
    
    
    public void setString (String astring){
        this.astring = astring;                
    }  
    
}

Here is the result come out to the screen:

User put in: 4444
class variable astring: null
class variable anumber: 4444
item selected: b
class variable astring: b
item selected: c
class variable astring: c
item selected: d
class variable astring: d
item selected: e
class variable astring: e
Process exited with exit code 0

I want those two variables to be set to what user entered and selected and they will be available to other classes, methods to use them.

You will have to rethink your logic. The values the user enters are not available until the user enters them and does something to cause an event. That event will cause a call to be made to your listener(s) where you can get what the user entered.
Now you need to call the methods that need those values and pass them the values.
You can see that the timing is different. The program must wait for the event generated by the user before it can get the values the user entered. Then the program can take those values and do what it wants with them.

You will have to rethink your logic. The values the user enters are not available until the user enters them and does something to cause an event. That event will cause a call to be made to your listener(s) where you can get what the user entered.
Now you need to call the methods that need those values and pass them the values.
You can see that the timing is different. The program must wait for the event generated by the user before it can get the values the user entered. Then the program can take those values and do what it wants with them.

I am sorry but I am now more confused. So in which part the problem would be? Is in my setString () method or in the itemStateChanged() method? Thanks.

You said this was the problem:

The problem is that I want those two variables to be set to what user entered and selected and they will be available to other classes, methods to use them.

Are those two values available to the program AFTER the user enters them?
If they are, then can you explain why you think you should be able to get the values BEFORE the user enters them?

You said this was the problem:

Are those two values available to the program AFTER the user enters them?
If they are, then can you explain why you think you should be able to get the values BEFORE the user enters them?

Yes. I think they are available to the program AFTER the user enters them. The evidence is that I can print both of them out to the screen. I do not think I will be getting the values BEFORE the user put in.

My goal is that the "anumber" will be set to the number users put in and the "astring" will be what users selected from the list. Then later if I have another class, I can get use of the two variables in my SampleGUI class. Something like this:

public class TestSampleGUI {
    public TestSampleGUI() {
    }
    
    public static void main(String args[]){
        SampleGUI sg = new SampleGUI();       
        System.out.println("class variable astring: " + sg.astring); // if user selected "a", I expect to "a" here
        System.out.println("class variable anumber: " + sg.anumber); // if user put in 1234, I expect to see that number here
        
    }
}

Just simple like that. Please just tell me where is the problem in my code. The number is set correct but the string is always null. Thanks.

If you want astring to have a value from the user when the constructor exits, then you will have to use the same technique you use to get anumber.
Use a modal dialog that presents a list and have the use select from the list. The modal dialog will not return until the user has made the selection.

If you want astring to have a value from the user when the constructor exits, then you will have to use the same technique you use to get anumber.
Use a modal dialog that presents a list and have the use select from the list. The modal dialog will not return until the user has made the selection.

Thanks NormR1. I really do not want to change much of the code but I guess I have no other choice. So I think I could use JOptionPane to do it. For example something like this:

Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,

        "Choose one", "Input",

        JOptionPane.INFORMATION_MESSAGE, null,

        possibleValues, possibleValues[0]);
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.