Search code examples
javajbuttonjtextfield

Using JTextField and JButton to open an url


I am trying to create connection between the JTextField , JButton and url that if i click the button the code opens the url for count purposes. I tried several way down below one of my attempt.

I get an error. How to fix that ?

 @Override
            public void actionPerformed(ActionEvent event) {
                String input  =   textField.getText();
                URL book = null;
                try {
                    book = new URL("input");
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                BufferedReader in = null;
                try {
                    in = new BufferedReader(new InputStreamReader(book.openStream(), StandardCharsets.ISO_8859_1));
                } catch (IOException e) {
                    e.printStackTrace();
                }

I get a very long error message here is a part of it:

java.net.MalformedURLException: no protocol: input
at java.net.URL.<init>(URL.java:593)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at Main$1.actionPerformed(Main.java:44)

Solution

  • You are trying to open the URL "input" (a String) instead of what you read from the textfield. PLease compare

    book = new URL("input");
    

    to

    book = new URL(input);