Home » Java » java – How to get TextField value from another class or method-Exceptionshub

java – How to get TextField value from another class or method-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I don’t know how JTextField works. I’m trying a lots.
My question is: How to get TextField value from another class or method?

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

public class MuGUI extends JPanel {
    public MyGui() {
        JTextField betText = new JTextField("");    
    }

    public void method2() {
        // error this line, cant find betText
        String value = betText.getText();
    }
How to&Answers:

You can declare your JTextField globally and then you initialize it inside your constructor. Now you have access to your variable in your methods too.

public class MyGUI extends JPanel
{
  private JTextField betText;

  public MyGUI(){
     //other operations
     betText = new JTextField("");
  }

  public void test(){
     String a = betText.getText();
  }
 }