简体   繁体   中英

Change JTextField from another Class Java/BlueJ

Im working on a project with JFrame (first time). I have some JTextFields and 1 JButton on the frame. So what I am trying to do is to edit text of my JTextField from another class. I'm entering 2 values in a JTextField and I want the outcome to be shown in another JTextField.

Whenever I press the Button I want one JTextField textfield9 to be changed into the value I calculated in my other class's method (in this case the totalHours() method in Module).

I've been trying a lot of examples I've found but none of them seems to worked for me T_T.

Here is te code I have problems with.

GUI Class:

private JButton button1;
private JTextField textfield5; // First value
private JTextField textfield7; // Second value
public JTextField textfield9;  // Outcome - I made it public because I would get an error of 'cannot find symbol setText()' in the Module Class (totalHours() method)

// So when I click on the Button I want the textfield9 to show the method (totalHours()) from the Module class
button1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) 
        {
            Module module = new Module();
            int text = module.totalHours();
            String textt = Integer.valueOf(text).toString();
            textfield9.setText(textt);
        }
    });

Module Class:

This is the outcome I want it to be shown in textfield9 whenever I click on the button on the frame

public int totalHours()
{
    int num1 = Integer.parseInt(getHoursWeek());        // getter from GUI Class - textfield5
    int num2 = Integer.parseInt(getTotalWeeksCourse()); // getter from GUI Class - textfield7
    int num3 = num1 * num2;
    gui.textfield9.setText(Integer.toString(num3));
    return num3;
}

I dont know why, but nothing is showing up in textfield9, instead it is opening another JFrame with 2 Exception:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at Module.totalHours(Module.java:49)
at GUI$1.actionPerformed(GUI.java:67)

It's these 2 lines:

int num1 = Integer.parseInt(getHoursWeek()); // Module Class totalHours() method
int text = module.totalHours();  // GUI Class button1 actionlistener

Here is the full code of both Classes. Deleting unnecessary lines.

GUI Class:

public class GUI extends JFrame 
{
    private JMenuBar menuBar;
    private JButton button1;
    private JLabel label5;
    private JLabel label7;
    private JLabel label9;
    private JTextField textfield5;
    private JTextField textfield7;
    public JTextField textfield9;

//Constructor 
public GUI()
{        
    setTitle("GUI");
    setSize(468,400);

    //pane with null layout
    JPanel contentPane = new JPanel(null);
    contentPane.setPreferredSize(new Dimension(468,400));
    contentPane.setBackground(new Color(192,192,192));

    button1 = new JButton();
    button1.setBounds(181,332,127,44);
    button1.setText("Invoer");

    button1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) 
        {
            Module module = new Module();
            int text = module.totalHours();
            String textt = Integer.valueOf(text).toString();
            textfield9.setText(textt);
        }
    });

    label5 = new JLabel();
    label5.setBounds(5,115,94,31);
    label5.setText("Module Nummer");

    label7 = new JLabel();
    label7.setBounds(274,14,156,33);
    label7.setText("Per module");

    label9 = new JLabel();
    label9.setBounds(276,57,90,35);
    label9.setText("Totaal uren");

    textfield5 = new JTextField();
    textfield5.setBounds(120,225,90,35);

    textfield7 = new JTextField();
    textfield7.setBounds(120,280,90,35);

    textfield9 = new JTextField();
    textfield9.setBounds(361,57,90,35);

    //adding components to contentPane panel
    contentPane.add(button1);
    contentPane.add(label5);
    contentPane.add(label7);
    contentPane.add(label8);
    contentPane.add(label9);
    contentPane.add(textfield5);
    contentPane.add(textfield7);
    contentPane.add(textfield9);

    //adding panel to JFrame and seting of window position and close operation
    getContentPane().add(contentPane);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    pack();
    setVisible(true);

    //initGUI();
}

 public static void main(String[] args)
 {
    System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() 
        {
            new GUI();
        }
    });
}

public String getTextfield1()
{
    String txtfield1 = textfield1.getText();
    return txtfield1;
}

public String getTextfield2()
{
    String txtfield2 = textfield2.getText();
    return txtfield2;
}

public String getTextfield3()
{
    String txtfield3 = textfield3.getText();
    return txtfield3;
}

public String getTextfield4()
{
    String txtfield4 = textfield4.getText();    
    return txtfield4;
}

public String getTextfield5()
{
    String txtfield5 = textfield5.getText();
    return txtfield5;
}

public String getTextfield7()
{
    String txtfield7 = textfield7.getText();
    return txtfield7;
}

public String getTextfield9()
{
    String txtfield9 = textfield9.getText();
    return txtfield9;
}
}

Module Class:

public class Module
{
private GUI gui;

/**
 * Constructor for objects of class Module
 */
public Module()
{
    gui = new GUI();
}

public String getCourseName()
{
    return gui.getTextfield1();
}

public String getSchoolDays()
{
    return gui.getTextfield2();
}

public String getModuleNumber()
{
    return gui.getTextfield3();
}

public String getWeekNumber()
{
    return gui.getTextfield4();
}

public String getHoursWeek()
{
    return gui.getTextfield5();
}

public String getTotalWeeksCourse()
{
    return gui.getTextfield7();
}

public int totalHours()
{
    int num1 = Integer.parseInt(getHoursWeek());    
    int num2 = Integer.parseInt(getTotalWeeksCourse());
    int num3 = num1 * num2;
    gui.textfield9.setText(Integer.toString(num3));
    return num3;
}
}

Sorry if it's hard to understand what I'm trying to say, never been good in explaining things. Could anyone help me out with this!?

The issue with your code is that you are creating a new Module object within your ActionListener inner class each time you click the button, which in turn creates a new GUI object and so on... You've also got a nasty potential loop - if you move the module out of the ActionListener, it will create a new GUI, which will create a new Module, create a new GUI and so on...

There are a few issues - I'll address them one by one:

Cyclical reference

Don't create a new GUI for each Module and a new Module for each GUI. Instead - have a field for the reference to the GUI and a setGUI() method in the Module:

public class Module
{
    private GUI gui;

    public void setGUI(GUI myGUI)
    {
        this.gui = myGUI;
    }
 ... // rest of Module class

call this from the GUI constructor ie

module.setGUI(this);

Creating Module objects in the ActionListener

Then problem is with this block of code:

   button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) 
    {
        Module module = new Module();
        int text = module.totalHours();
        String textt = Integer.valueOf(text).toString();
        textfield9.setText(textt);
    }
});

In particular - this line:

Module module = new Module();

You need a single instance of the Module object referenced from your GUI object. Then, you read the totalHours from that same object every time. There are a few different options for how you do this - I'll propose one:

  1. Have module as a field in your GUI class
  2. Make the GUI class implement ActionListener
  3. add your actionPerformed method to the GUI class:

    public void actionPerformed(ActionEvent evt) { int text = module.totalHours(); String textt = Integer.valueOf(text).toString(); textfield9.setText(textt); }

  4. replace your current code for adding the action listener with button1.addActionListener(this);

Exception on receiving nothing from the totalHours() method

You see

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

If you look down the stack trace - you find something like:

at Module.totalHours(Module.java:49)

When you look at your totalHours() method, it is reading the GUI textfields and trying to parse them into integers. They are empty (unless you've typed something into them), so parseInt is trying to create an integer from an empty string (""). You need to add some error checking to that method.

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