Search code examples
javaswingjtextfield

how to make JTextField input accessable in other classes


I am trying to make my JTextField input visible to my other classes. I am not going to clog up the page with a ton of code, just where the problem is.

I have done a ton of online research but I am getting nowhere.

public class browseropen extends JFrame { 

    public browseropen() {
        setDefaultCloseOperation(EXIT_ON_CLOSE); // setting app close on exit 
        JPanel panel = new JPanel(); // creating new app panel

        JTextField urltxt = new JTextField(10); // establishing new text field for URL input
        urltxt.addActionListener(new ActionListener() { // adding event for enter key
            @Override
            public void actionPerformed(ActionEvent event ) {
                runClient();              // run browser open command
            }
        });

        public String geturltxt() { // attempting to set input of JTextField to be available in other class

                    return urltxt.getText();

                }

I would appreciate any insight as I am just starting to learn Java and want to learn the right way :)

Edit: the problem is in geturltxt


Solution

  • The easy answer is: turn that local variable into a field of your class, like

    public class BrowserOpen extends JFrame {
      private final JTextField urltxt; // to be init'ed in your constructor for example
    

    And voila, now your other methods can use that field urltxt.

    Notes: please read about java coding styleguides to get your class/field names "right".