Search code examples
javaswingclassjtextfield

Change jTextField from another class


I have two different classes which creates two Panel's A & B. B is initiated after a button is click on A. I want to change the a jTextField in B, when a button is clicked on A.

Code of A

private final B myB = new B();

public static void main(String args[])
    {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new A().setVisible(true);
            }
        });
    }

Initiation of B

private void btnIPCStartActionPerformed(java.awt.event.ActionEvent evt) 
    {                                            
        // TODO add your handling code here:
        launch.B.main(null);
    }

Change of jTextField in B

private void btnBattRemoveActionPerformed(java.awt.event.ActionEvent evt)                                              
    {      
        **// Calling Via Variable**                                                  
        myB.txtSystemOutput.setText("Low Battery"); // **NOT Working**

        **// Calling Via Setter**
        myB.setTextSystemOutput("Low Battery"); // **NOT Working**

        **// Calling Via Direct Variable**
        project.B.txtSystemOutput.setText("Low Battery"); // **NOT Working**
    }

Code of B

public static void main(String args[])
    {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new B().setVisible(true);
            }
        });
    }

public void setTextSystemOutput(String value)
    {
        txtSystemOutput.setText(value);
    }

Solution

  • You don't want to create B by calling its static main method as that is unnecessary and harmful since it isolates the B visualized instance from your A object. Instead create a B instance in A, create it in the non-static world, and this way, A can call instance variables on B as needed.

    So change method to:

    private void btnIPCStartActionPerformed(java.awt.event.ActionEvent evt) {                                            
       myB.setVisible(true);
    }