Hot questions for Using JTextField in oop

Question:

I am working on a payroll program for school. I only two weeks into working with GUIs so my skills have a lot of room for growth. Everything works fine except for this method. I am trying to get the method to clear the JTextAreas if the number entered is out of range and skip the remaining code that sends the data to the JTextArea. As of now, it prints out the name, dept and 0.00 if out of range but I do not want it to display anything unless it is within range.

public void buildAgain() {

    // declare variables to hold the JTextField input as string
    String rateStr, hoursStr, firstName, lastName, dept;


    firstName = (String) fnameField.getText();
    lastName = (String) lnameField.getText();

    rateStr = rateField.getText();
    // convert the rate field into double in order to calculate it
    rate = Double.parseDouble(rateStr);


    hoursStr = hoursField.getText();
    // convert the hours into double in order to calculate it
    hoursWorked = Double.parseDouble(hoursStr);

    // Check how many hours worked to make sure they are within range
    if(hoursWorked >= 0 && hoursWorked <=60)
        hours = hoursWorked;

    // Display message if hours are not within range
    else
        JOptionPane.showMessageDialog(null, "You have entered an invalid number of hours. \n"
                          + " Please enter a number between 0 and 60.", "Hour Entry Error", 
                          JOptionPane.ERROR_MESSAGE);

    // Clears JTextFields after the error message
    fnameField.setText("");
    lnameField.setText("");
    hoursField.setText("");
    rateField.setText("");

    // check the hourly rate to make sure it is within  range
    if (rate >= 6 && rate <=150)
        payRate = rate;

    // display an error message if rate entered not within range
    else 
        JOptionPane.showMessageDialog(null, "You have entered an invalid pay rate. \n "
                          + "Please enter the rate between 6 and 150.", "Pay Rate Error", 
                           JOptionPane.ERROR_MESSAGE);

    // clear the JTextFields  after error message
    fnameField.setText("");
    lnameField.setText("");
    hoursField.setText("");
    rateField.setText("");

    // calculate the pay regular hours
    if (hours >= 0 && hours <= 40){
        weeklyPay = hours*payRate;

    // Calculate overtime pay
    } else if (hours > 40 && hours <= 60){
        overTime = (hours-40) * (payRate*1.5);
        weeklyPay = overTime + (40*payRate);
    }

    // Display the total pay in uneditable table
    totalPayField.setText("$"+dollar.format(weeklyPay));

    // Send name to JTextArea
    list.append(firstName + " ");
    list.append(lastName);

    // Get the selected department
    if(hr.isSelected())
        dept = hr.getText();
    else if(accounting.isSelected())
        dept = accounting.getText();//"Accounting";
    else if(marketing.isSelected())
        dept = marketing.getText();
    else if(sales.isSelected())
        dept = sales.getText();
    else
        dept = shipping.getText();

    // Send selected department and pay to JTextArea
    list.append("\t" + dept);
    list.append("\t$" + dollar.format(weeklyPay) + "\n");

    }

Answer:

You're almost there.

Move the section of code where you clear your JTextFields before the section of code where you check hours worked are within range. Then return just after you show your error message. That way execution of the method does not continue.

//Clears JTextFields before checking the error message
fnameField.setText("");
...

//check how many hours worked to make sure they are within range
if(hoursWorked >= 0 && hoursWorked <=60)
    hours = hoursWorked;

//Display message if hours are not within range
else
    JOptionPane.showMessageDialog(null, "error msg.\n", JOptionPane.ERROR_MESSAGE);
    return

Note: If you only want the fields cleared after theres an error then move them into the else statement where the error message is shown.

Ex:

//check how many hours worked to make sure they are within range
if(hoursWorked >= 0 && hoursWorked <=60) {
    hours = hoursWorked;

//Display message if hours are not within range
} else {
    JOptionPane.showMessageDialog(null, "error msg.\n", JOptionPane.ERROR_MESSAGE);
    //Clears JTextFields before checking the error message
    fnameField.setText("");
    ...
    return
}

Question:

I am still quite new to coding and I am hitting a bit of a wall right now.

I have an array of strings that I use in a loop to build a JLabel and a corresponding JTextField.

String[] textFieldList = {"Name", "Age", "Height", "weight"};

formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
for (String tfL : textFieldList) {
    JLabel jl = new JLabel(tfL);
    JTextField jtf = new JTextField("");
    jtf.setName(tfL);
    formPanel.add(jl);
    formPanel.add(jtf);
}
addPanel.add(formPanel, BorderLayout.CENTER);

I have a save button that I want to retrieve the all of entered values, so I am trying to use the same array to get the name of each JTextField by using the same array of strings to get the value of each text field.

I have not yet been able to successful build a loop that has worked for me yet.

saveBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {     
        for (String tfL : textFieldList) {              
            tfL.getText()                   
        }
    }
});

Is there a way that I can build the loop correctly to return the string results and can I test the returned values to see if they should be parsed as ints.

If anyone could point me in the right direction it would be great.


Answer:

all you need to do is create jtextfield array and use normal loop instead enhanced .in your code you can't use tfL.getText() because tfL is a String not a jtextfield .but in my code i have decalared textfield array named jtextf so you can get values using .getText()

 JTextField[] jtextf;// global variable

 String[] textFieldList = {"Name", "Age", "Height", "weight"};
 jtextf=new JTextField[textFieldList.length];

 formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));

    for (int i=0;i<textFieldList.length;i++) {

        JLabel jl = new JLabel(tfL);
        jtextf[i] = new JTextField("");
        jtextf[i].setName(textFieldList[i]);
        formPanel.add(jl);
        formPanel.add(jtextf[i]);
    }
}

when you want to retieve use

saveBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {     
        for (JTextField field: jtextf) {              
            field.getText()                   
        }
    }
});

Question:

Is it possible to create multiple JTextFields with different names inside a loop? I need to so this since I later need to get the text that is in each of them, I need to do something like this:

while (sst_ResultSet.next()) {
    p_vertabla.add(new JLabel(sst_ResultSet.getString(1));
    p_vertabla.add(new JTextField(sst_ResultSet.getString(1)));
}

This works just fine when adding the JLabel and the JTextField the way I want it to the JPanel p_vertabla, but I don't know how to later call the method .getText(); on the JTextFields.


How can I create the JTextFieldsin the loop or how can I later call the method on them?


Answer:

You can create a Vector<JTextField> and add to it the generated items in your for loop:

while (sst_ResultSet.next()) {
    p_vertabla.add(new JLabel(sst_ResultSet.getString(1));
    createAndKeepJTextFieldInVector(sst_ResultSet.getString(1));
    // instead of original: p_vertabla.add(new JTextField(sst_ResultSet.getString(1)));
}

Then later, you could access any of the JTextFields by calling:

String txt = vector.get(index).getText();

Question:

I am making an application in Netbeans and I would like to get the text from the jTextField and set it to a jLabel that is in another jFrame (not the same!)

I did this:

jLabel.setText(jTextField1.getText());

But it doesn't work. And what event method should I use? actionPerformed?


Answer:

Forget about JFrames, forget about JTextFields and JLabels, but instead look at your question in its most basic essence which is:

I want to change the state of one object based on the state of another.

That's it in a nutshell.

This can be easily solved by giving one class a getter/accessor method that extracts the desired information -- here the text in the JTextField, e.g.

public String getFieldText() {
    return myTextField.getText();
}

and giving the other class a setter/mutator method that allows outside objects to inject the desired information, here to set the text of its JLabel

public void setLabelText(String text) {
    myLabel.setTexzt(text);
}

The devil of course is when to call one or both of these methods, and where, and that will depend on much that you haven't told us, but likely one or both of these methods will be called in event code, such as in an ActionListener's actionPerformed method.

Question:

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

   public class Excercise24_19 extends JFrame
   {
     private static int[][] grid = new int[10][10]; //creates a grid

   public static void main(String[] args)
   {


     Excercise24_19 frame = new Excercise24_19(); //creates the frame

     frame.setTitle("Excercise 24_19"); //title of window
     frame.setLocationRelativeTo(null); //sets location to middle of screen
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setVisible(true); //displays the window
   }

   public Excercise24_19()
   {
     createMatrix(); //creates matrix of numbers inside "grid"
     setLayout(new GridLayout(10, 10)); //sets a 10 x 10 layout
     String temp; //creates a temp variable to hold number's as string

     for(int i = 0; i < grid.length-1; i++)
     {
       for(int j = 0; j < grid[i].length-1; j++)
         {
           temp = "" + grid[i][j] + "";
           matrix.add(new JTextField(temp, 2));
         }
     }
   }

   public static void createMatrix()
   {
     Random myRand = new Random();
     for(int i = 0; i < grid.length-1; i++)
      {
        for(int j = 0; j < grid.length-1; j++)
        {
          grid[i][j] = myRand.nextInt(2);
        }

      }

   }
 } 

PROBLEM: I must create a 10x10 grid with random numbers and use JTextField so that I can change the numbers on the spot. The program must then find the biggest block (Algorithm of O(n^2) complexity) of 1's in the matrix and highlight them red.

Not implemented yet are the listeners or buttons for the other part of this program, and code that finds the largest block of 1's.

My problem is how to i center the text on the JTextFields? Its bothering me because I am not creating variable names for the textfields but I don't see how I am suppossed to center the text inside using ".setHorizontalAlignment(JTextField.CENTER);"

Also will I be able to create listeners for the textfields in case i do change the numbers.

If it helps this is what the end program is suppsed to look like:

This is what my program looks like now:

Thank you in advance for your help!


Answer:

You have to give the text field a variable name if you want to change its settings. Change this line:

matrix.add(new JTextField(temp, 2));

to these lines:

JTextField text = new JTextField(temp, 2));
text.setHorizontalAlignment(JTextField.CENTER);
matrix.add(text);

Question:

Okay I've a problem with a swing event listener... Short introduction I develop a Java application with a Swing UI structured by the MVC pattern.

  • MyView -> The text is changed by the user and the view should inform model by controller
  • MyModel -> Store the data and inform view about changes through controller
  • MyController -> Interface used to inform model and view about changes

Based on this classes model and view are only connected through the controller class. The view class contains a text field for user input which should update the model class with the user input without pressing a button. This means I need a listener for JTextField that waits for user input/change of text...

I tried DocumentListener but it doesn't work, a exception is thrown: java.lang.IllegalStateException: Attempt to mutate in notification

I think the problem here is that the model class called also the controller if properties changed and the controller informs/changes the view again -> Result: Infinity loop

Both solutions I found didn't work for me:

Swing JTextField on text change

JTextField listener when text changes that modifies textField's text

MyModel.java

public void setHost(String host) // Method called by controller to change model
{
    String oldHost = this.host;
    this.host = host;

    this.firePropertyChange("Host", oldHost, this.host); // Model inform view about changes
}

MyView.java

@Override public void modelPropertyChange(final PropertyChangeEvent event)
{
    // Method used to update view and called by controller

    if(event.getPropertyName().equals("Username"))
    {
        String username = (String) event.getNewValue();
        this.nameField.setText(username);
    }
}

The problem is when the document listener is called because the user input something the model is changed call the property changed method of view and view replace the text with the same text which raise again a document changed event and the listener is called... Infinity loop

I tried to work with an ActionListener it works fine but it is necessary for the user to press return to assign the changes... Are there any other options to listen for text changes in a JTextField without DocumentListener? Or what should I changed by my MVC pattern to solve this issue?

EDIT

I tried the solution of Peter Walser but a new exception was thrown:

java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.x1c1b.carrierpigeon.service.mvc.AbstractController.setModelProperty(AbstractController.java:62)
at org.x1c1b.carrierpigeon.desktop.ui.controller.LoginController.changeUsername(LoginController.java:12)
at org.x1c1b.carrierpigeon.desktop.ui.view.LoginView$UsernameChangedListener.updateFieldState(LoginView.java:221)
at org.x1c1b.carrierpigeon.desktop.ui.view.LoginView$UsernameChangedListener.insertUpdate(LoginView.java:203)
at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:201)
at javax.swing.text.AbstractDocument.handleInsertString(AbstractDocument.java:748)
at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:707)
at javax.swing.text.PlainDocument.insertString(PlainDocument.java:130)
at org.x1c1b.carrierpigeon.desktop.ui.util.TextFieldLimit.insertString(TextFieldLimit.java:26)
at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:669)
at javax.swing.text.JTextComponent.replaceSelection(JTextComponent.java:1328)
at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(DefaultEditorKit.java:884)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1668)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2882)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2929)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2845)
at java.awt.Component.processEvent(Component.java:6316)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:835)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1103)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:974)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:800)
at java.awt.Component.dispatchEventImpl(Component.java:4760)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1338)
    at javax.swing.text.AbstractDocument.replace(AbstractDocument.java:658)
    at javax.swing.text.JTextComponent.setText(JTextComponent.java:1669)
    at org.x1c1b.carrierpigeon.desktop.ui.view.LoginView.modelPropertyChange(LoginView.java:76)
    at org.x1c1b.carrierpigeon.service.mvc.AbstractController.propertyChange(AbstractController.java:47)
    at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
    at org.x1c1b.carrierpigeon.service.mvc.AbstractModel.firePropertyChange(AbstractModel.java:27)
    at org.x1c1b.carrierpigeon.desktop.ui.model.LoginModel.setUsername(LoginModel.java:39)
    ... 52 more

It seems like the document of JTextField is still locked during inform the model, because it calls the method setText the exception is thrown and this operation is illegal but I can't figure out why?!

EDIT

For now I solved this bug by the instructions and the first solution of Peter Walser combined with executing the instructions set by the DocumentListener on the EDT!


Answer:

There are two approaches to properly solve this:

Fire a property change event only if actually something changed

There's no point in notifying if the property value is the same as before (not changed at all). Avoiding the unnecessary event will effectively break your loop:

public void setHost(String host) {
  // check if property actually changed
  if (Objects.equals(this.host, host) return;
  String oldHost = this.host;
  this.host = host;
  this.firePropertyChange("Host", oldHost, this.host); 
}

or (fancy compact form):

public void setHost(String host) {
    if (!Objects.equals(this.host, host)) {
        firePropertyChange("Host", this.host, this.host=host);
    }
}
Do one-way synchronization to avoid cascades

Changing a propery in the model can change a property in the view can change a property in the model can change... - this can quickly run in circles.

To break these cascades, do a one-way synchronization: while the model notifies the view about changes, ignore any cascading updates.

To do so, you need a flag on the controller (in your case, the view holding the microcontrollers a.k.a. Swing listeners):

MyView.java:

boolean updating;

@Override public void modelPropertyChange(final PropertyChangeEvent event)
{
    if (updating) {
        // cascading update, ignore
        return;
    }
    updating=true;
    try {
        if(event.getPropertyName().equals("Username")) {
        {
            String username = (String) event.getNewValue();
            this.nameField.setText(username);
        }
        ...
    }
    finally {
        updating=false;
    }
}

The first approach is pretty straightforward (but can get complicated when dealing with complex objects and collections). The second approach is easy and more forgiving by design - view always represents model (no changes missed), and cascading updates are blocked.

Question:

I know i need this code looped but I'm not sure how to do it, like i don't know what to have as the loop? it clears all the textfields at the minute, but i only want the textfield that has anything but an integer cleared. any help would be appreciated.

try {
    int a = Integer.parseInt(theApp.tred.getText());
    int b = Integer.parseInt(theApp.tgreen.getText()); // uses
                                                        // information
                                                        // entered
    int c = Integer.parseInt(theApp.tblue.getText());

    if (a < 0) {
        a = 200; // if statements for values above and below the targets
                            // set
        tred.setText("200");
    }

    if (a > 255) {
        a = 255;
        tred.setText("255");
    }
    if (b < 0) {
        b = 200;
        tgreen.setText("200");
    }

    if (b > 255) {
        b = 255;
        tgreen.setText("255");
    }

    if (c < 0) {
        c = 200;
        tblue.setText("200");
    }
    if (c > 255) {
        c = 255;
        tblue.setText("255");
    }
    message.setText(" work submitted by:"); // text
    message.setForeground(new Color(a, b, c)); // changes colour to
                                                        // desired input

} catch (NumberFormatException ex) {

    message.setText("invalid input! please enter numbers only"); // text
    message.setForeground(new Color(0, 0, 0)); // original text set to
                                                // red
    tred.setText("");
    tgreen.setText("");
    tblue.setText(""); // clears box if not an integer
}

Answer:

You can separate the try-catch block into 3 parts:

int a = -1;
try {
    a = Integer.parseInt(theApp.tred.getText());
    if (a < 0) {
        a = 200; 
        tred.setText("200");
    }
    if (a > 255) {
        a = 255;
        tred.setText("255");
    }
    //do the needed things here
} catch (Exception e) {
    message.setText("invalid input! please enter numbers only"); // text
    message.setForeground(new Color(0, 0, 0)); 
    tred.setText("");
}

(this is just for tred, the others are pretty much the same).

Question:

I want to force a textfield to only accept letters and white space. I tried this function that looks fine to me but it only prints:

accepted and i=0 So I can see that it's a problem of local variable or smthg like that;

public void ff()
{Boolean bool=true;
int i=0;


     name=textField.getText();
     while(bool && i<name.length())
     {
         if(Character.isLetter(name.charAt(i)))
             i++;
         else
            bool=false;
     }
    if (bool=true) 
            System.out.println("accepted"+i);
    else 
            System.out.println("wrong"+i);

}

Can you help me to figure it out? and Please I want to use this function not documentfilter or formattedtext.


Answer:

bool=true is assignment, not comparison.

Change if (bool=true) to if (bool==true) or if (bool). Otherwise, you'll always print accepted.

Question:

My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?

Please note the code below has been altered to the correct working version provided all the helpful contributors below.

Main class:

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

class MyFileLister extends JPanel implements ActionListener {

private JLabel prompt = null;

private JTextField userInput = null;

private JTextArea textArea = null;

public MyFileLister()
{
    prompt = new JLabel("Enter filename: ");
    prompt.setOpaque(true);
    this.add(prompt);

    userInput = new JTextField(28);
    userInput.addActionListener(this);
    this.add(userInput);

    textArea = new JTextArea(10, 30);
    textArea.setOpaque(true);
    JScrollPane scrollpane = new JScrollPane(textArea);
    this.add(textArea, BorderLayout.SOUTH);
}

Scanner s = null;
File af = null;
String[] paths;

public void actionPerformed(ActionEvent f)
{
    try
    {
        s = new Scanner(new File(userInput.getText()));

        while(s.hasNextLine())
        {
            String as = s.nextLine();
            textArea.append(as + "\n");
            textArea.setLineWrap(truea);
        }

    }
    catch(FileNotFoundException e)
    {
        af = new File(userInput.getText());

        paths = af.list();
        System.out.println(Arrays.toString(paths));

        String tempPath = "";
        for(String path: paths)
        {
            tempPath += path + "\n";
        }

        textArea.setText(tempPath);
    }
}
}

Driver class:

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


class TestMyFileLister {

public static void main(String [] args)
{
    MyFileLister thePanel = new MyFileLister();

    JFrame firstFrame = new JFrame("My File Lister");

    firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    firstFrame.setVisible(true);
    firstFrame.setSize(500, 500);
    firstFrame.add(thePanel);


}
}

Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.

I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.

public void actionPerformed(ActionEvent f)
{       
    try
    {
        s = new Scanner(new File(userInput.getText()));

        if(af == null)
        {
            System.out.println("Error");
        }

        while(s.hasNextLine())
        {
            String as = s.nextLine();
            textArea.append(as + "\n");
            textArea.setLineWrap(true);
        }

    }
    catch(FileNotFoundException e)
    {
        af = new File(userInput.getText());

        paths = af.list();
        System.out.println(Arrays.toString(paths));

        String tempPath = "";
        for(String path: paths)
        {
            tempPath += path + "\n";
        }

        textArea.setText(tempPath);
    }   
}

Answer:

You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).

     // These lines below are causing only last file shown.

    for(String path: paths)
    {
        textArea.setText(path);
    }

Here is your modified version for MyFileLister class :

public class MyFileLister extends JPanel implements ActionListener {

private JLabel prompt = null;  
private JTextField userInput = null;    
private JTextArea textArea = null;

public MyFileLister()
{
    prompt = new JLabel("Enter filename: ");
    prompt.setOpaque(true);
    this.add(prompt);

    userInput = new JTextField(28);
    userInput.addActionListener(this);
    this.add(userInput);

    textArea = new JTextArea(10, 30);
    textArea.setOpaque(true);
    JScrollPane scrollpane = new JScrollPane(textArea);
    this.add(scrollpane, BorderLayout.SOUTH);
}

Scanner s = null;
File af ;
String[] paths;

public void actionPerformed(ActionEvent f)
{
    try
    {
        s = new Scanner(new File(userInput.getText()));

        while(s.hasNext())
        {
            String as = s.next();
            textArea.setText(as);
        }

    }
    catch(FileNotFoundException e)
    {
        af = new File(userInput.getText());

        paths = af.list();
       System.out.println(Arrays.toString(paths));

       String tempPath=""; 
        for(String path: paths)
        {
           tempPath+=path+"\n";

        }
        textArea.setText(tempPath);

    }
}
}

Output :

Question:

Im having trouble on calling my Loop that i created to be placed on the JTextField. Im only a beginner on GUI so i don't understand what i am missing or lacking . Please Help me.
the program must print a box of period if the user enters 1 and box of asterisk if the user
enters 2. and if the user enters 2 or more an error message will show up.

I re-editted the code sir. this is what i came up, the problem is after i re-enter a number the Jtextarea just keeps stacking the print, it does not refresh i don't know why.Example is if i enter 1 the box of periods will shop then if i enter 2 the box of asterisk appears below the box of periods .and it just keeps on stacking

    import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Box extends JFrame{

    private JLabel numL,resultL;
    private JTextField numTF;
    private JTextArea resultTF;
    private JButton printB,exitB;
    private PrintButtonHandler pbHandler;
    private ExitButtonHandler exitHandler;




    public Box(){

        numL=new JLabel("Enter 1 or 2", SwingConstants.CENTER);
        resultL=new JLabel("Result",SwingConstants.CENTER);
        numTF=new JTextField(20);
        //resultTF=new JTextField(20);
        resultTF = new JTextArea(5,5);

        printB=new JButton("Print");
        pbHandler=new PrintButtonHandler();
        printB.addActionListener(pbHandler);


        exitB=new JButton("Exit");
        exitHandler= new ExitButtonHandler();
        exitB.addActionListener(exitHandler);


        setTitle("BOX");

        Container p=getContentPane();
        p.setLayout(new GridLayout(5,1));

        p.add(numL);
        p.add(numTF);
        p.add(resultL);
        p.add(resultTF);
        p.add(printB);
        p.add(exitB);

        setSize(600,600);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }


        private class PrintButtonHandler implements ActionListener{
            public void actionPerformed(ActionEvent e){
               //Box1 p=new Box1();
                int num,height=5,width=5,numLL;
                  numLL=Integer.parseInt(numTF.getText());

                Font f = resultTF.getFont();
                resultTF.setFont(new Font(Font.MONOSPACED, f.getStyle(), f.getSize()));





            if(numLL==1){
                for(int i = 0; i < 5; i++) {
                 for(int j = 0; j < 5; j++) {
                resultTF.append(".");
                }
                resultTF.append("\n");
                }

            }else if(numLL==2){
                for(int i = 0; i < 5; i++) {
                 for(int j = 0; j < 5; j++) {
                resultTF.append("*");
                }
                resultTF.append("\n");
                }
            }else if(numLL>2){
                resultTF.append("NOT 1 OR 2:");

            }
            }
        }

        private class ExitButtonHandler implements ActionListener{
            public void actionPerformed(ActionEvent e){

                System.exit(0);

            }
        }

        public static void main(String[]args){
            Box p=new Box();
        }
}

Answer:

Right now you are directing your boxes to System.out. So you need to direct them to your text component.

Also, you can't use JTextField for this because it is not multiline. Instead, you should use something like a JTextArea inside a JScrollPane.

resultTF = new JTextArea();
Font f = resultTF.getFont();
resultTF.setFont(new Font(Font.MONOSPACED, f.getStyle(), f.getSize()));

add(new JScrollPane(resultTF));

.
.
.

for(int i = 0; i < height; i++) {
    for(int j = 0; j < width; j++) {
        resultTF.append(".");
    }
    resultTF.append("\n");
}

If you don't want a scroll pane, you could also, for example, create the text area with specific rows and columns (new JTextArea(5, 5)), use a StringBuilder to create your box and use setText instead of append.

As a side note, you should be creating your GUI on the Swing event thread. In other words, your main should be wrapped in a call to invokeLater:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Box p = new Box();
        }
    });
}

See also:

Question:

I am trying to create a student registration program in which the user inputs data in a JFrame in a JTextField and that data is stored into a variable in another class. package acgregistration;

import java.util.*;
/**
*
* @author Frank
*/
public class AcgRegistration {


public static void main(String[] args) {

    memberDialogBox memberDialogBox = new memberDialogBox();

}

}



    package acgregistration;

    /**
     *
     * @author Frank
     */
    class acgMember {
 private String name;
 private int num;
 private String email;

 public acgMember(String name, int number, String email) {
    this.name = name;
    this.num = number;
    this.email = email;
 }

 public String getName() {
    return name;
 }

 public void setName(String name) {
    this.name = name;
 }

 public int getNum() {
    return num;
 }

 public void setNum(int num) {
     this.num = num;
 }

 public String getEmail() {
    return email;
 }

 public void setEmail(String email) {
    this.email = email;
 }
 }



 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 /**
 *
 * @author Frank
 */
 public class memberDialogBox {

 String options[] = {"Student","Faculty/Staff"};
 JComboBox choices = new JComboBox(options);
 JButton b = new JButton("Confirm");
 JLabel l = new JLabel("Select your ACG Status");

 public memberDialogBox(){
  frame();
 }

 public void frame(){

  JFrame f = new JFrame();
  f.setVisible(true);
  f.setSize(210,150);
  f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  JPanel p = new JPanel();
  p.add(choices);
  p.add(b);
  p.add(l);

  f.add(p);

  b.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){


          String s = choices.getSelectedItem().toString();
          if ("Student".equals(choices.getSelectedItem())){

               studentDialogBox student = new studentDialogBox();
    //This code gives me an error code saying I should call 
   //acgMemberModel


          }
          else{
                 facultyDialogBox faculty= new facultyDialogBox();
              }

        f.dispose();
          }

  });
  }

 }


 package acgregistration;
 import javax.swing.*;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class studentDialogBox { 
private JTextField nameField = new JTextField("", 20);
private JTextField emailField = new JTextField("", 20);
private JTextField numberField = new JTextField("", 20);
private JButton confirmButton = new JButton("Confirm");
private acgMemberModel model;


public studentDialogBox(acgMemberModel model) {
    this.model = model;
    frame();
}



public void frame() {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.add(nameField);
    panel.add(emailField);
    panel.add(numberField);
    panel.add(confirmButton);
    frame.add(panel);

    confirmButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String name = nameField.getText();
            String number = numberField.getText();
            String email = emailField.getText();
            acgMember member = new acgMember(name, 
   Integer.valueOf(number), email);
            model.addNew(member);
        }
    });

   }
 }

class acgMemberModel {
private List<acgMember> members = new ArrayList<>();

public void addNew(acgMember member) {
    members.add(member);
}

public List<acgMember> getMembers() {
    return Collections.unmodifiableList(members);
}
}

I'm basically trying to do this for all the text fields and then save it into an ArrayList or a Hashmap ( basically the end result). My only question is, how would i store text field inputs from one class to another? Any help would be highly appreciated! Thank you!


Answer:

Just create new instance of Member every time when you populate fields and push button in result of this action listener will invoked and you will grab all data from text field and pass it to new instance constructor. Every time you create new Member pass it to MemberModel separate class.

P.S. you need to read something about naming convention of java language especially about variables, you made mistake in way to set action listener to a TextField instead of Button because your variable names completely meaningless. I refactor code in way to change all variable names to human readable form and fix mistake in my solution because all that conventions has not been used.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        MemberModel model = new MemberModel();
        StudentsToOutputListener outputListener
                = new StudentsToOutputListener(model, new FileOutput(new File("path to your default file")));
        Window studentDialog = new StudentDialogBox(model);
        Window facilityDialog = new FacultyDialogBox();
        Window memberDialog = new MemberDialogBox(studentDialog, facilityDialog);
        memberDialog.show();
    }
}

class Member {
    private String name;
    private int number;
    private String email;

    public Member(String name, int number, String email) {
        this.name = name;
        this.number = number;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Member{" +
                "name='" + name + '\'' +
                ", number=" + number +
                ", email='" + email + '\'' +
                '}';
    }
}

interface Window {
    void show();
}

interface Output {
    void output(List<Member> members);
}

interface Listener {
    void update();
}

class MemberDialogBox implements Window {
    private JFrame frame = new JFrame();
    private JComboBox<Window> choiceComboBox = new JComboBox<>();
    private JButton confirmButton = new JButton("Confirm");
    private JLabel selectLabel = new JLabel("Select your ACG Status");

    public MemberDialogBox(Window... windows) {
        for (Window window : windows) {
            choiceComboBox.addItem(window);
        }
        frame();
    }


    public void show() {
        frame.setVisible(true);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(210, 150);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(choiceComboBox);
        panel.add(confirmButton);
        panel.add(selectLabel);
        frame.add(panel);

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Window window = (Window) choiceComboBox.getSelectedItem();
                window.show();
                frame.dispose();
            }

        });
    }

}

class StudentDialogBox implements Window, Listener, Output {
    private JTextField nameField = new JTextField("", 20);
    private JTextField emailField = new JTextField("", 20);
    private JTextField numberField = new JTextField("", 20);
    private JButton confirmButton = new JButton("Confirm");
    private JButton saveButton = new JButton("Save students to file");
    private JFrame frame;
    private JList<Member> list = new JList<>();
    private MemberModel model;


    public StudentDialogBox(MemberModel model) {
        this.model = model;
        model.addListener(this);
        frame();
    }


    public void show() {
        frame.setVisible(true);
    }


    public void output(List<Member> members) {
        list.setListData(members.toArray(new Member[]{}));
    }


    public void update() {
        model.outputStudentsTo(this);
    }

    public void frame() {
        frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.add(nameField);
        panel.add(emailField);
        panel.add(numberField);
        panel.add(confirmButton);
        panel.add(list);
        panel.add(saveButton);
        frame.add(panel);

        saveButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.showSaveDialog(frame);
                File selectedFile = fileChooser.getSelectedFile();
                Output output = new FileOutput(selectedFile);
                model.outputStudentsTo(output);
            }
        });

        confirmButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String name = nameField.getText();
                String number = numberField.getText();
                String email = emailField.getText();
                Member member = new Member(name, Integer.valueOf(number), email);
                model.addNewStudent(member);
            }
        });

    }


    public String toString() {
        return "Student";
    }
}

class FacultyDialogBox implements Window {

    public void show() {
        System.out.println("you need to implement FacultyDialogBox " +
                "in similar way than StudentDialog box");
    }


    public String toString() {
        return "Faculty/Stuff";
    }
}


class MemberModel {
    private List<Member> students = new ArrayList<>();
    private List<Member> stuff = new ArrayList<>();
    private List<Listener> listeners = new ArrayList<>();

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    private void notifyListeners() {
        for (Listener listener : listeners) {
            listener.update();
        }
    }

    public void addNewStudent(Member member) {
        students.add(member);
        notifyListeners();
    }

    public void addNewStuff(Member member) {
        stuff.add(member);
        notifyListeners();
    }

    public void outputStudentsTo(Output output) {
        output.output(Collections.unmodifiableList(students));
    }

    public void outputStuffTo(Output output) {
        output.output(Collections.unmodifiableList(stuff));
    }
}

class FileOutput implements Output {
    private final File destination;

    public FileOutput(File destination) {
        this.destination = destination;
    }

    public void output(List<Member> members) {
        try (BufferedWriter file = new BufferedWriter(new FileWriter(destination))) {
            for (Member member : members) {
                file.write(member.toString());
                file.write("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

class StudentsToOutputListener implements Listener {
    private final MemberModel model;
    private final Output output;

    public StudentsToOutputListener(MemberModel model, Output output) {
        this.model = model;
        this.output = output;
        model.addListener(this);
    }

    public void update() {
        model.outputStudentsTo(output);
    }
}

I update answer to you question clarification, i understand what do you want to implement and fix your program, also i refactor this code and make it more in oop style and more readable, but you need to implement by yourself second dialog Facility in similar way than Student dialog box. Also you need to place every class in this source to different *.java file.