简体   繁体   中英

For a JTextField, how do I set text from another class?

I have looked around other threads and can't find a working solution.

My program reads a file, splits up each word in a line and stores in an array. If what is searched for is in array[0], then I would like to output the array into its corresponding text fields.

I am trying to test it by just setting the text for 1 text field (ID text field) but the text field is not being populated with text. This is my code so far:

GUI - StudentUI

public class StudentUI extends javax.swing.JFrame {

/**
 * Creates new form StudentUI
 */
public StudentUI() {
    initComponents();
    saveBtn.setVisible(false);
}

final String FILENAME = "Students.txt";

private void initComponents() {

    searchTxt = new javax.swing.JTextField();
    idLbl = new javax.swing.JLabel();
    titleLbl = new javax.swing.JLabel();
    forenameLbl = new javax.swing.JLabel();
    surnameLbl = new javax.swing.JLabel();
    address1Lbl = new javax.swing.JLabel();
    address2Lbl = new javax.swing.JLabel();
    postcodeLbl = new javax.swing.JLabel();
    numberLbl = new javax.swing.JLabel();
    birthLbl = new javax.swing.JLabel();
    idTxt = new javax.swing.JTextField();
    forenameTxt = new javax.swing.JTextField();
    surnameTxt = new javax.swing.JTextField();
    address1Txt = new javax.swing.JTextField();
    address2Txt = new javax.swing.JTextField();
    postcodeTxt = new javax.swing.JTextField();
    numberTxt = new javax.swing.JTextField();
    birthTxt = new javax.swing.JTextField();
    searchBtn = new javax.swing.JButton();
    searchLbl = new javax.swing.JLabel();
    titleCombo = new javax.swing.JComboBox<>();
    addBtn = new javax.swing.JButton();
    editBtn = new javax.swing.JButton();
    deleteBtn = new javax.swing.JButton();
    saveBtn = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    idLbl.setText("ID");

    titleLbl.setText("Title");

    forenameLbl.setText("Forename");

    surnameLbl.setText("Surname");

    address1Lbl.setText("Address 1");

    address2Lbl.setText("Address 2");

    postcodeLbl.setText(" Postcode");

    numberLbl.setText("Phone Number");

    birthLbl.setText("Date of Birth (DD/MM/YYYY)");

    searchBtn.setText("Search");
    searchBtn.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            searchBtnActionPerformed(evt);
        }
    });


public void setTextField(JTextField jTF, String value) {
    jTF.setText(value);
}

private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
    int count = Search.totalLines(FILENAME);
    Search.linear(FILENAME, count, searchTxt.getText());
}                                         

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new StudentUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton addBtn;
private javax.swing.JLabel address1Lbl;
private javax.swing.JTextField address1Txt;
private javax.swing.JLabel address2Lbl;
private javax.swing.JTextField address2Txt;
private javax.swing.JLabel birthLbl;
private javax.swing.JTextField birthTxt;
private javax.swing.JButton deleteBtn;
private javax.swing.JButton editBtn;
private javax.swing.JLabel forenameLbl;
private javax.swing.JTextField forenameTxt;
private javax.swing.JLabel idLbl;
private javax.swing.JTextField idTxt;
private javax.swing.JLabel numberLbl;
private javax.swing.JTextField numberTxt;
private javax.swing.JLabel postcodeLbl;
private javax.swing.JTextField postcodeTxt;
private javax.swing.JButton saveBtn;
private javax.swing.JButton searchBtn;
private javax.swing.JLabel searchLbl;
private javax.swing.JTextField searchTxt;
private javax.swing.JLabel surnameLbl;
private javax.swing.JTextField surnameTxt;
private javax.swing.JComboBox<String> titleCombo;
private javax.swing.JLabel titleLbl;
// End of variables declaration                   
}

Search Class

public class Search {

public static int totalLines(String filename) {
    int n = 0;
    String currentLine;
    try {
        FileReader fr = new FileReader(filename);
        BufferedReader br = new BufferedReader(fr);
        while ((currentLine = br.readLine()) != null) {
            n = n + 1;
        }

    } catch (Exception e) {

    }

    return n;
}

public static void linear(String filename, int lines, String searchItem) {
    String currentLine;

    try {
        FileReader fr = new FileReader(filename);
        BufferedReader br = new BufferedReader(fr);
        while ((currentLine = br.readLine()) != null) {
            String[] array = new String[lines];
            array = currentLine.split(",");
            if (array[0].equals(searchItem)) {
                StudentUI student = new StudentUI();
                student.setTextField(student.idTxt, array[0]);
            }
        }

    } catch (Exception e) {

    }
}

}

You've a big problem here at (A):

public static void linear(String filename, int lines, String searchItem) {
    String currentLine;

    try {
        FileReader fr = new FileReader(filename);
        BufferedReader br = new BufferedReader(fr);
        while ((currentLine = br.readLine()) != null) {
            String[] array = new String[lines];
            array = currentLine.split(",");
            if (array[0].equals(searchItem)) {
                StudentUI student = new StudentUI();  // ****** (A) ******
                student.setTextField(student.idTxt, array[0]);
            }
        }

    } catch (Exception e) {
        // ****** (B) ******
    }
}

You're creating a new StudentUI() object -- a new one, one completely different from the StudentUI that is already displaying, and so setting the state of its JTextField will have no effect on the currently displayed StudentUI object.

A wrong solution is to make the JTextField variable static -- don't do this as you'd be throwing out the OOP baby with the bath water by doing this.

A better solution is to pass a reference to the currently displayed StudentUI object to his method, so that you can change the state of the object of interest.


Other problem at (B) -- don't ignore exceptions in this way, since by doing this, if your code crashes, you won't know why.


So one way to solve this is to give the linear method a StudentUI parameter:

public static void linear(StudentUI student, String filename, int lines, String searchItem) {

    String currentLine;

    try {
        FileReader fr = new FileReader(filename);
        BufferedReader br = new BufferedReader(fr);
        while ((currentLine = br.readLine()) != null) {
            String[] array = new String[lines];
            array = currentLine.split(",");
            if (array[0].equals(searchItem)) {
                //  StudentUI student = new StudentUI();  // ****** (A) ******
                student.setTextField(student.idTxt, array[0]);
            }
        }

    } catch (Exception e) {
        e.printStacktrace();  // ****** (B) *******
    }
}

And then call it, passing this into the method as the first parameter.

Also, notice that I'm now printing the exception's stacktrace so that I can see if/when an exception is thrown, what caused it and where.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM