This tutorial will cover a Http Client server application GET/POST GUI Connection in Java. This is tutorial part two for creating the client side application. The goal of this tutorial is to create a GUI application that connects to web and shows addition of two numbers. Part one of this tutorial where we server side application can be found here: Http Client server application GET/POST . In this tutorial, I am using NetBeans IDE and Glassfish Server. Focus of this application are following:

  • Create user Interface for GUI using netbean
  • Connect Java GUI application that can take input from webserver

Create a new Java application from File > New Project > Java and select Java application. Then click Next and type in Project name. Please unchecked Create main class.

You will see that a new Java application project have been created. Do a right-click on default Package and click on New > JFrame Form. Now provide class name as ClientServerApp and Package name as com.serverapp . Click on finish.

You will see something like this while creating JFrame class.

Now we have to create GUI layout. My GUI layout was like following:

To create GUI layout like above, Start adding following gui elements to create above GUI layout:

  1. Add Two label and name it  Number 1  and Number 2
  2. Two text field and remove the default text by doing a right click and Edit text. Also change the variable name. In this tutorial I have added  txtNumOne for first text field and txtNumTwo for second text field.
  3. Add one one button and name it Submit. Change the variable name to btnSubmit
  4. Add one text area and change the variable name to btnSubmit textAreaResult

You will see some auto generated code for your class. At first check that java package name and imports looks like following. Or else import the missing ones. :

package com.serverapp;
/*
Written By Garnel K at www.bytetips.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

Now write following code which will connect our java gui application.

private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String numb1 = txtNumOne.getText().trim();
        String numb2 = txtNumTwo.getText().trim();

        if (numb1 != null && numb2 != null) {
            BufferedReader reader = null;

            try {
                URL url = new URL("https://localhost:8080/ClientServerWeb/MyServlet?num1="+numb1+"&num2="+numb2);
                URLConnection con = url.openConnection();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String line;
                while ((line = reader.readLine()) != null) {
                    textAreaResult.append(line + "\n");
                }
            } catch (MalformedURLException ex) {
                Logger.getLogger(ClientServerApp.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ClientServerApp.class.getName()).log(Level.SEVERE, null, ex);

            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        Logger.getLogger(ClientServerApp.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }                                         

Following code is getting value for numb1 and numb2 variable using text field:

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String numb1 = txtNumOne.getText().trim();
        String numb2 = txtNumTwo.getText().trim();

Then we are using URL/host form Tutorial one : Http Client server application GET/POST  Then we are using simple try /catch and exception handling to ensure the code quality.

Here is the full source code after cleaning unwanted auto generated comment:

package com.serverapp;

/*
Written By Garnel K at www.bytetips.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ClientServerApp extends javax.swing.JFrame {

    /**
     * Creates new form ClientServerApp
     */
    public ClientServerApp() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtNumOne = new javax.swing.JTextField();
        txtNumTwo = new javax.swing.JTextField();
        btnSubmit = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textAreaResult = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Number 1");

        jLabel2.setText("Number 2");

        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        textAreaResult.setColumns(20);
        textAreaResult.setRows(5);
        jScrollPane1.setViewportView(textAreaResult);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSubmit)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(86, 86, 86)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtNumTwo, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
                            .addComponent(txtNumOne)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNumOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNumTwo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnSubmit)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
        );

        pack();
    }//                         

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
        String numb1 = txtNumOne.getText().trim();
        String numb2 = txtNumTwo.getText().trim();

        if (numb1 != null && numb2 != null) {
            BufferedReader reader = null;

            try {
                URL url = new URL("https://localhost:8080/ClientServerWeb/MyServlet?num1="+numb1+"&num2="+numb2);
                URLConnection con = url.openConnection();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                String line;
                while ((line = reader.readLine()) != null) {
                    textAreaResult.append(line + "\n");
                }
            } catch (MalformedURLException ex) {
                Logger.getLogger(ClientServerApp.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ClientServerApp.class.getName()).log(Level.SEVERE, null, ex);

            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        Logger.getLogger(ClientServerApp.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientServerApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientServerApp().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnSubmit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea textAreaResult;
    private javax.swing.JTextField txtNumOne;
    private javax.swing.JTextField txtNumTwo;
    // End of variables declaration                   
}

Now you are ready to run you java application. Select your web app and run it. Then select your java app and run it. If you have any question please feel free to comment.

By Garnel

I like to write about Tips And Tutorials related topics and I blog about my personal interests. I am trying to learn the ways to Promote Blog. Sharing my limited knowledge with the world. Blogging about Tips, Tutorials, and Tweaks for Computers, Internet, Operating System, Windows Xp, Windows Vista, Office Applications, Gadgets, Science, and Technology. And Having Fun..

Leave a Reply

Your email address will not be published. Required fields are marked *

two × one =