Search code examples
javaswingjpaneljtextfield

How to get TextField value from another class or method


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();
    }

Solution

  • 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();
      }
     }