Search code examples
javaswingjframejtextfield

How to read user input from JTextfield in another class Java


I am trying to create a desktop application that will open a specified URL.

I am using Java to build the app and here is my code so far.

browseropen.java

 public class browseropen {


    public static void main(String[] args) {

            JFrame frame = new JFrame("Desktop Browser Search"); // We create our initial app frame
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // next we are making sure our app stops running
            JPanel panel = new JPanel(); // Our new application window
            JLabel optext = new JLabel("Welcome Please Enter URL to Begin!"); // Our new window text
            frame.setSize(400, 400); // Set Application Window Size
            //pack();
            // Now adding Text box
            JTextField txtbox = new JTextField(10);
            JButton gourl = new JButton("Go To URL"); // creating new button to activate browser function
            frame.setVisible(true);
            optext.setVisible(true);
            frame.setLayout( new GridLayout(3,4,5,10));
            panel.add(optext); // We are adding our objects to our app window
            panel.add(txtbox);
            panel.add(gourl);
            frame.add(panel); // And finally we add our app panel to our frame 
            String geturl = txtbox.getText();


     gourl.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             //run client main
             runClient();
         }




public void runClient() {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            String[] args1={"10"};
            openbrowserurl.main(args1);
        }
    });
}
});
    }

    public void texturl() {



    };



}

openbrowser.java

public class openbrowserurl extends browseropen {

    public static void main(String[] args)  {

        Desktop desktop = Desktop.getDesktop();
        String urlinput = "https://www.google.com";
        if( !java.awt.Desktop.isDesktopSupported() ) {
            System.err.println("Desktop Not Supported");
            System.exit(1);
        }
        if (args.length == 0) {
              System.out.println( "Usage: OpenURI [URI [URI ... ]]" );
                System.exit( 0 );
        }

        if(!desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {

            System.err.println( "Desktop doesn't support the browse action (fatal)" );
            System.exit( 1 );
        }

        for ( String arg : args ) {

            try {

                java.net.URI uri = new java.net.URI( urlinput );
                desktop.browse( uri );
            }
            catch ( Exception e ) {

                System.err.println( e.getMessage() );
            }
    }

}
}

I can open a specified URL if it is specified inside the openbrowser.java, but I want to read the value of the JTextField I created in browseropen.java.


Solution

  • You currently can't get information from the JTextField within the browseropen class because it is declared within a static main method and thus is visible only within that method. Your whole project screams to us -- he doesn't yet know about object-oriented programming or how Java implements it, since this is what is hampering your attempts.

    Suggestions:

    • First of all, learn about object oriented programming with Java, including use of non-static methods and fields. There are many tutorials on this that are easy to find including those that can be found here: The Really Big Index
    • Make your browseropen more "OOP" compliant by giving it non-static fields and methods, including a private JTextField field.
    • Give it a public method that returns the String held by the JTextField
    • Don't have your openbrowserurl class extend the browseropen as that makes no sense. Instead have the first class contain an instance of the second class.

    Other issues:

    • It's good that you're trying to use layout managers rather than the null layout and setBounds(...), but I'm confused about just what you're trying to do. You set the JFrame's layout to a GridLayout, one that expects 3 rows and 4 columns (12 components in all), and yet you only add one component to the JFrame, the "panel" JPanel. I'm not sure what you're trying to do, making it difficult what to advise in this situation.

    For instance, you could create a class like so:

    public class GetUrlPanel extends JPanel {
        private static final String PROMPT = "Welcome Please Enter URL to Begin!";
        private JTextField urlField = new JTextField(10);
        private JButton goToUrlButton = new JButton("Go To URL");
    
        public GetUrlPanel() {
            add(new JLabel(PROMPT));
            add(urlField);
            add(goToUrlButton);
        }
    
        public String getUrlFieldText() {
            return urlField.getText();
        }
    
        public void addGoToUrlListener(ActionListener listener) {
            goToUrlButton.addActionListener(listener);
        }
    }
    

    which would allow outside classes to display this JPanel wherever it is needed, would allow them to decide what to do when the button is pushed, and would allow them to extract the contents of the JTextField.

    Another option is to get the URL more simply from a JOptionPane, such as:

    public static void main(String[] args) {
        if (!Desktop.isDesktopSupported()) {
            System.err.println("Desktop is not supported. Exiting");
            System.exit(1);
        }
        String message = "Welcome Please Enter URL to Begin!";
        String title = "Enter URL";
        int messageType = JOptionPane.PLAIN_MESSAGE;
        String url = JOptionPane.showInputDialog(null, message, title, messageType);
        if (url == null) {
            System.err.println("Cancelled by user");
            System.exit(0);
        } else if (url.trim().isEmpty()) {
            System.err.println("You must enter a URL. Exiting");
            System.exit(2);
        }
    
    
        URI uri = null;
        try {
            uri = new URI(url);
            Desktop desktop = Desktop.getDesktop();
            desktop.browse(uri);
        } catch (URISyntaxException | IOException e) {
            String text = "Invalid URL \"" + url + "\". Exiting";
            System.err.println(text);
            e.printStackTrace();            
        }
    }
    

    There are lots of ways to skin this cat, but if there is one and only one thing that I want to stress in answering this question it is this:

    You will want to study and learn OOPS concepts and techniques before doing anything else.