Showing posts with label Swing. Show all posts

Sample Client - Server Chat Application in Java

Client Server ChatApplication

Wikipedia: A network socket is an endpoint of an inter-process communication flow across a computer network.

Difference between Server and Client
Server Socket is one that accept connection on specific port and can respond. Where client can send message to server on specified port and can get response from server.

We will send messages over network only. In this demo application I'm sending and receiving messages on localhost. To create full-fledged chat application you need to modify many things like...

  • Every system must have Socket Server running on local system to accept messages from another system.
  • Get list of all system which is running your application. 
  • If you are planning to create rich chat application, provide advance settings like Save chat log, Play sound when receives message, Send encrypted messages, etc... can be lot more.

Note: There will be plenty of code which is not explained in all source code which was generated by NetBeans IDE. NetBeans project code attached at the end of article.

Socket Server
It will accept connection and listen for messages and pass it to desired frame/user chat window. I create Server in form JFrame just to give better look.
/*
 * mainFrame.java
 * This program demonstarte client server message application.
 * mainFrame.java will act as a server program aimed to receive messages and respond to client.
 */
package com.javaquery.frames;

import java.awt.Frame;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.UIManager;
import org.json.JSONObject;

public class mainFrame extends javax.swing.JFrame {

    /* Inner class to create socket server */
    private class mainServer extends Thread {

        /* Create ServerSocket variable */
        private ServerSocket serverSocket;

        /* Constructor to initialize serverSocket */
        public mainServer() throws IOException {
            serverSocket = new ServerSocket(6666);
        }

        /* Implement run() for Thread */
        public void run() {
            /* Keep Thread running */
            while (true) {
                try {
                    /* Accept connection on server */
                    Socket server = serverSocket.accept();
                    /* DataInputStream to get message sent by client program */
                    DataInputStream in = new DataInputStream(server.getInputStream());
                    /* We are receiving message in JSON format from client. Parse String to JSONObject */
                    JSONObject clientMessage = new JSONObject(in.readUTF());
                    
                    /* Flag to check chat window is opened for user that sent message */
                    boolean flagChatWindowOpened = false;
                    /* Reading Message and Username from JSONObject */
                    String userName = clientMessage.get("Username").toString();
                    String message = clientMessage.getString("Message").toString();
                    
                    /* Get list of Frame/Windows opened by mainFrame.java */
                    for(Frame frame : Frame.getFrames()){
                        /* Check Frame/Window is opened for user */
                        if(frame.getTitle().equals(userName)){
                            /* Frame/ Window is already opened */
                            flagChatWindowOpened = true;
                            /* Get instance of ChatWindow */
                            ChatWindow chatWindow = (ChatWindow) frame;
                            /* Get previous messages from TextArea */
                            String previousMessage = chatWindow.getjTextArea1().getText();
                            /* Set message to TextArea with new message */
                            chatWindow.getjTextArea1().setText(previousMessage+"\n"+message);
                        }
                    }
                    
                    /* ChatWindow is not open for user sent message to server */
                    if(!flagChatWindowOpened){
                        /* Create an Object of ChatWindow */
                        ChatWindow chatWindow = new ChatWindow();
                        /**
                         * We are setting title of window to identify user for next message we gonna receive
                         * You can set hidden value in ChatWindow.java file.
                         */
                        chatWindow.setTitle(userName);
                        /* Set message to TextArea */
                        chatWindow.getjTextArea1().setText(message);
                        /* Make ChatWindow visible */
                        chatWindow.setVisible(true);
                    }
                    
                    /* Get DataOutputStream of client to repond */
                    DataOutputStream out = new DataOutputStream(server.getOutputStream());
                    /* Send response message to client */
                    out.writeUTF("Received from "+clientMessage.get("Username").toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * To start SocketServer when mainFrame.java loads
     */
    public void startServer() {
        try {
            /* Create thread of Inner class mainServer */
            Thread t = new mainServer();
            /* Start Thread */
            t.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        lblInformation = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server");
        setAlwaysOnTop(true);

        lblInformation.setText("Client - Server Sample Application");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInformation)
                .addContainerGap(229, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInformation)
                .addContainerGap(275, Short.MAX_VALUE))
        );

        pack();
    }//                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                /* To set new look and feel */
                JFrame.setDefaultLookAndFeelDecorated(true);
                try {
                    /**
                     * Change look and feel of JFrame to Nimbus 
                     * For other look and feel check
                     * 
                     */
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (Exception ex) {
                   ex.printStackTrace();
                }
                /* Create an Object of mainFrame */
                mainFrame mFrame = new mainFrame();
                /* make mainFrame visible */
                mFrame.setVisible(true);
                /* Call startServer method  */
                mFrame.startServer();
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JLabel lblInformation;
    // End of variables declaration                   
}

Chat Window Source Code
ChatWindow.java is common class which creates Chat window for user. We are identify particular user's chat window by its title. You can have your logic.
package com.javaquery.frames;

public class ChatWindow extends javax.swing.JFrame {

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

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        lblInfo = new javax.swing.JLabel();
        scrollPane = new javax.swing.JScrollPane();
        chatArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Message Box");

        lblInfo.setText("Messages");

        chatArea.setColumns(20);
        chatArea.setRows(5);
        scrollPane.setViewportView(chatArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(lblInfo))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInfo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }//                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ChatWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextArea chatArea;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JScrollPane scrollPane;
    // End of variables declaration                   

    /**
     * @return the chatArea
     */
    public javax.swing.JTextArea getjTextArea1() {
        return chatArea;
    }

    /**
     * @param chatArea the chatArea to set
     */
    public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
        this.chatArea = jTextArea1;
    }
}

Client Source Code
This will send message to sever and get response. We are sending 3 messages to server. Two messages from same username.
/*
 * client.java
 * This program demonstarte client server message application.
 * client.java will act as a client program aimed to send messages and get server response
 */

package com.javaquery.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.json.JSONObject;

public class client {

    public static void main(String[] args) {
        client c = new client();
        /* Create JSON variable */
        JSONObject transmitJSON = new JSONObject();

        /**
         * This is sample program so we are sending three messages from same system with different username.
         * In your case you'll receive message from multiple systems.
         */
        /* Fill up JSON variable with message and username */
        transmitJSON.put("Message", "Hello JavaQuery!");
        transmitJSON.put("Username", "Vicky.Thakor");
        /* Send message to server */
        c.sendMessage("localhost", transmitJSON.toString());
        
        transmitJSON.put("Message", "Hello Apple!");
        transmitJSON.put("Username", "Steve.Jobs");
        /* Send message to server */
        c.sendMessage("localhost", transmitJSON.toString());
        
        transmitJSON.put("Message", "How are you?");
        transmitJSON.put("Username", "Steve.Jobs");
        /* Send message to server */
        c.sendMessage("localhost", transmitJSON.toString());
    }

    /**
     * @author javaQuery
     * @param host
     * @param message 
     */
    public void sendMessage(String host, String message) {
        try {
            /* Create new socket connection with server host using port 6666 (port can be anything) */
            Socket client = new Socket(host, 6666);
            /* Get server's OutputStream */
            OutputStream outToServer = client.getOutputStream();
            /* Get server's DataOutputStream to write/send message */
            DataOutputStream out = new DataOutputStream(outToServer);
            /* Write message to DataOutputStream */
            out.writeUTF(message);
            /* Get InputStream to get message from server */
            InputStream inFromServer = client.getInputStream();
            /* Get DataInputStream to read message of server */
            DataInputStream in = new DataInputStream(inFromServer);
            /* Print message received from server */
            System.out.println("Server says..." + in.readUTF());
            /* Close connection of client socket */
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Download Project

How to get list of opened JFrame in Java Swing?


Swing
Swing is built on base of Abstract Window Toolkit. Swing is used to create desktop application. Swing is using AWT directly or indirectly to provide you richer user interface. Swing is placed under javax.swing

JFrame can be accessible by its parent.



Understanding the Diagram
As you can see I created boundary around Parent JFrame, Child JFrame 1 and Child JFrame 2. It means you can access list of JFrame initiated by ParentJFrame. You can't access Standalone JFrame in Parent JFrame.


Frame.getFrames()
This method will return list of all Frame Object created by its parent and parent it self.


Parent JFrame Source Code
import java.awt.Frame;

public class ParentJFrame extends javax.swing.JFrame {

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

    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        lblInfo = new javax.swing.JLabel();
        btnOpenChildJFrame = new javax.swing.JButton();
        btnListJFrames = new javax.swing.JButton();
        scrollPane = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Parent JFrame");

        lblInfo.setText("Parent JFrame");

        btnOpenChildJFrame.setText("Open Child JFrame");
        btnOpenChildJFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenChildJFrameActionPerformed(evt);
            }
        });

        btnListJFrames.setText("List JFrame");
        btnListJFrames.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListJFramesActionPerformed(evt);
            }
        });

        textArea.setColumns(20);
        textArea.setRows(5);
        scrollPane.setViewportView(textArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                    .addComponent(lblInfo)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnOpenChildJFrame)
                        .addGap(18, 18, 18)
                        .addComponent(btnListJFrames)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInfo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOpenChildJFrame)
                    .addComponent(btnListJFrames))
                .addGap(18, 18, 18)
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// //GEN-END:initComponents

    /**
     * Open Child JFrame button click event
     */
    private void btnOpenChildJFrameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenChildJFrameActionPerformed
        /* Create an object of childJFrame */
        childJFrame child = new childJFrame();
        /* Make childJFrame visible */
        child.setVisible(true);
    }//GEN-LAST:event_btnOpenChildJFrameActionPerformed

    /**
     * List JFrame button click event
     */
    private void btnListJFramesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListJFramesActionPerformed
        /* Get previous text of JFrame */
        String previousText = textArea.getText();
        String strNewFrames = "";
        /* It will give you list of JFrame created/Initiated by ParentJFrame */
        for(Frame frame: Frame.getFrames()){
            strNewFrames += frame.getTitle() + "\n";
        }
        /* Set text of JTextArea */
        textArea.setText(previousText+strNewFrames);
    }//GEN-LAST:event_btnListJFramesActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ParentJFrame().setVisible(true);
            }
        });
    }

    private javax.swing.JButton btnListJFrames;
    private javax.swing.JButton btnOpenChildJFrame;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTextArea textArea;
}

Child JFrame Source Code
public class childJFrame extends javax.swing.JFrame {

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

    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {

        lblInfo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Child JFrame");

        lblInfo.setText("Child JFrame");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInfo)
                .addContainerGap(188, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInfo)
                .addContainerGap(91, Short.MAX_VALUE))
        );

        pack();
    }// //GEN-END:initComponents

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new childJFrame().setVisible(true);
            }
        });
    }
    private javax.swing.JLabel lblInfo;
}
I used NetBeans to create sample code. I explained code that relate the title of article. Major code done only in Parent JFrame. Child JFrame only supports example.

How to apply/set up swing look and feel?

Swing application allows us to change the Look and Feel of the frame and its internal components as well. UIManager.setLookAndFeel() method used with different arguments to change its look.

Swing look and feel

We'll achieve blow swing Look and Feel
  • Metal - javax.swing.plaf.metal.MetalLookAndFeel
  • Nimbus - com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
  • CDE/Motif - com.sun.java.swing.plaf.motif.MotifLookAndFeel
  • Windows - com.sun.java.swing.plaf.windows.WindowsLookAndFeel
  • Windows Classic - com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel

To achieve Look and Feel add the code before it get visible. You have to copy just try-catch block in below code. If you set look and feel to parent Jframe. It also affect look to the children (calling other frame). Check the below code snippet. You have to uncomment the line for your desired look.
public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                /* It represent the frame border as internal jframe.
                 * However it only works with metal look and feel.
                 */
                //JFrame.setDefaultLookAndFeelDecorateld(true); 
                try {
                   //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                }
                new LookAndFeel().setVisible(true);
            }
        });
}

Understanding basics java.awt.Desktop

I was finding some good topic to write an article. So looking all around my projects. I used java.awt.Desktop class in my program. Lets discuss all about the Desktop class of java.

What is java.awt.Desktop?
          java.awt.Desktop class designed to interact with system programs. It executes the system command to handle the operation of file and sometime URL(s). So now lets take a look at the methods of Desktop class. All methods throws IOException so use try-catch.

Desktop.getDesktop().browse(URI uri)
This function is used to open URL Uniform (or universal) Resource Locator. This will open the URL in system's default web browser client.
Desktop.getDesktop().browse(URI.create("http://www.javaquery.com"));

Desktop.getDesktop().edit(File file)
It'll open file specified in parameter with system related editor. Say your file is .txt, .docx, etc... Be careful with this because if there ain't any editor related to that file type it'll throws error  java.io.IOException: Failed to edit file:/c:/1.pdf. Error message: Unspecified error. I'm trying to edit .pdf file which is not supported by my system.
Desktop.getDesktop().edit(new File("c:\\1.txt"));

Desktop.getDesktop().isSupported(Action action)
This method designed to check that system user has enough privileges to do operation. System admin can set  file open, edit, print, browse and mail permission of other users. It'll return true and false based on permission.
Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
Desktop.getDesktop().isSupported(Desktop.Action.EDIT);
Desktop.getDesktop().isSupported(Desktop.Action.PRINT);
Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
Desktop.getDesktop().isSupported(Desktop.Action.MAIL);

Desktop.getDesktop().mail()
It'll open the default mail client program of system.

Desktop.getDesktop().mail(URI uri)
Helps to set email, subject, message, cc and bcc on system default mail client. Predefined subject of mail and To so user don't need to remember your mail id or support mail id.
// To set space use "%20"
Desktop.getDesktop().mail(URI.create("mailto:vkijust4u@javaquery.com?subject=Hello%20World&body=This%20is%20sample%20mail&cc=example@gmail.com&bcc=example@yahoo.com"));

Desktop.getDesktop().open(File file)
Open the specified file in system's default program.
Desktop.getDesktop().open(new File("c:\\1.pdf"));

Desktop.getDesktop().print(File file)
Print the specified file in system's default printer.
Desktop.getDesktop().print(new File("c:\\1.pdf"));

Desktop.isDesktopSupported()
Tests whether this class is supported on the current platform. If it's supported, use Desktop.getDesktop() to retrieve an instance.

JClock (javaQuery.swing.JClock) A Swing class for clock

Introducing whole new class JClock for swing application. I was thinking for a long, why there ain't any component for displaying clock in swing application. Finally I coded JClock.java class. So let's have a look at coding part.
Swing JClock
JClock
/*
 * JClock(JLabel clock, boolean hour, boolean minute, boolean second, boolean AM_PM)
 * Pass the label reference you want to display clock
 * Indicate the time flag as per your need
 * You can change the Clock text size, color, font, etc... by providing JLabel property
 */
import javaQuery.swing.JClock;
JClock javaQueryClock = new JClock(jLabel1,true,true,true,true);

So its simple and easy to implement in your swing application. You can have your JLabel properties as it is. Happy Coding...


JTable (javax.swing.JTable) basics explained

Importance of Jtable in Desktop application.
If you are beginner then you must know why and how to use JTable. Table really important component of all programming language. Whether you work around web application, desktop application or consider database.

             Jtable helps you to organize your data in proper manner. Let say you want to show all your employee's details. Jtable is your option.


Today's agenda for JTable
  • How to change width of column in JTable?
  • How to change height of cell in JTable?
  • How to disable column in JTable?
  • How to disable row in JTable?

How to change width of column in JTable?
jTable1.getColumnModel().getColumn(2).setMaxWidth(70);
jTable1.getColumnModel().getColumn(2).setMinWidth(70);

How to change height of cell in JTable?
private void updateRowHeights() {
   try {
        for (int row = 0; row < jTable1.getRowCount(); row++) {
            int rowHeight = jTable1.getRowHeight();
            for (int column = 0; column < jTable1.getColumnCount(); column++) {
               Component comp = jTable1.prepareRenderer(jTable1.getCellRenderer(row, column), row, column);
               rowHeight = Math.max(rowHeight, comp.getPreferredSize().height + 20);
               //Change the rowHeight in above line
            }
          jTable1.setRowHeight(row, rowHeight);
       }
   } catch (ClassCastException e) {
       e.printStackTrace();
   }
}

How to disable column in JTable? , How to disable row in JTable?
Object[][] rowData = new Object[10][2];
        Object columnNames[] = {"Column 1", "Column 2"};
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                if (column == 1 || row == 5 || row == 10) {
                    return false;//the nth row, column is not editable  
                }
                return true;
        }
};

Other article related to JTable :
How to update jtable dynamically from Oracle , MySQL (Database)?
http://www.javaquery.com/2010/10/how-to-update-jtable-dynamically-from.html
How to implement JButton in JTable?
http://www.javaquery.com/2013/05/how-to-implement-jbutton-in-jtable.html
How to implement JComboBox in JTable?
http://www.javaquery.com/2013/05/how-to-implement-jcombobox-in-jtable.html

How to implement JButton in JTable?

I was working on Inventory management project where i have to place button on jTable that shows order. I googled and found solution but he didn't provided proper information with all code. I'm gonna explain it properly with all basic code.

jTable, jButton
jTable - jButton

Source : http://tips4java.wordpress.com/2009/07/12/table-button-column/
Download : http://www.camick.com/java/source/ButtonColumn.java
                      - Download the ButtonColumn.java class file and place it in proper package. Don't forget to include your package in starting of code.

String[] InvoiceArray = new String[20];
//Declare above variable globally. Used by two-three methods. Change variable name as per your need.

/* 
 * import the ButtonColumn class if you are not working in IDE
 * I used formWindowOpened event to load content in Jtable but you can use other event.
 * All you need is put the code with in that event.
 */
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[4][2]; // 4: is number of row ; 2: is number of column
        Object columnNames[] = {"Invoice No", "View Report"}; // Name of columns
        for (int i = 0; i < 4; i++) {
            InvoiceArray[i] = i + "-2345";
            rowData[i][0] = i + "-2345";
            rowData[i][1] = "View Order " + i; // Can change the text of button.
        }
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
        jTable1.setModel(tm);
        ButtonColumn buttonColumn = new ButtonColumn(jTable1, showOrder, 1); // 1: is column number. column count starts with 0,1,2...
}

Now lets have a look on code snippet to handle the button click event. We find the button row index onclick and get the value from InvoiceArray by matching index.

Action showOrder = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
       //JTable table = (JTable) e.getSource(); // If you have multiple component following the ActionEvent
            int modelRow = Integer.valueOf(e.getActionCommand());
            if (InvoiceArray[modelRow] != null) {
                /* We are placing invoice no in array 
                 * And track the button click index
                 * And fetch index in invoice no
                 */
                System.out.println("Your Invoice No:" + InvoiceArray[modelRow]);
            } else {
                JOptionPane.showMessageDialog(rootPane, "No records found!");
            }
        }
};

How to implement JComboBox in JTable?

JTable and ComboBox
JTable and ComboBox
Its very tough for beginner to implement JComboBox with in JTable. I thought let me explain this example with all basic requirement one require. We're going to perform the below operations on JComboBox.

  • Implement JComboBox in JTable.
  • JComboBox value from Database.
  • Database index of the selected JComboBox.

So lets not waste time and take a look at the code. First of all you'll have to decide when the JTable update its model or say it's data. I used formWindowOpened event to load data in JTable.

private JComboBox comboBox;
//Above variable declared globally.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[5][1];
        Object columnNames[] = {"Name of Item"};
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
        jTable1.setModel(tm);
        /*
         * Below method creates the JComboBox in JTable. Check the method code below.
         * jTable1.getColumnModel().getColumn(0) : set the column index as per your need.
         */
        setItemNameColumn(jTable1.getColumnModel().getColumn(0));
}
private void setItemNameColumn(TableColumn itemColumn) {
        comboBox = new JComboBox();
        try {
            Connection con = variables.getDatabaseConnection();
            PreparedStatement item_stmt = con.prepareStatement("select idwarehouse,NameOfProduct from warehouse;");
            ResultSet item_rs = item_stmt.executeQuery();
            while (item_rs.next()) {
                comboBox.addItem(new Item(item_rs.getInt("idwarehouse"), item_rs.getString("NameOfProduct")));
               // Bind Name of product and index in ComboBox
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        comboBox.addActionListener(this); // Set action listener 
        itemColumn.setCellEditor(new DefaultCellEditor(comboBox));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        itemColumn.setCellRenderer(renderer);
}

// Bean for ComboBox
public class Item {
        private int id;
        private String description;
        public Item(int id, String description) {
            this.id = id;
            this.description = description;
        }
        public int getId() {
            return id;
        }
        public String getDescription() {
            return description;
        }
        public String toString() {
            return description;
        }
}
// Action listner that read the selected index every time and shows database index.
@Override
public void actionPerformed(ActionEvent e) {
   if (e.getSource().equals(comboBox)) {
         comboBox = (JComboBox) e.getSource();
         Item item = (Item) comboBox.getSelectedItem();
         if(item!=null){
              System.out.println("Database Index:"+item.getId());
         }
   }
}
That's it. All you need to put all code in your project. If you have any problem comment here. 

How to bind images - icon in .jar file?

                        This is really easy task however its seems hard for beginners. You can bind *.jpg, *.png, *.gif in .jar file. I didn't try other file types. If some other file type is working comment it in the article. Anyways this comes in picture when you are dealing with Graphical User Interface (GUI) application. All you need to put images, icons, etc... in your project.

Hoping you are using package phenomenon in your project. It shows neat and clean programming style. It'll help you and other team member to find proper class in proper package. Below is the image of my test project for javaquery.

Java Project Structure

I used com.javaquery.images package to place all my required images. Lets roll for the code... 

How to set button, menu item, label, frame image in netbeans?

Step 1: Store image in proper package.
Step 2: [If required: Goto Windows > Properties . It'll show properties of object in sidebar.] Select object and go to icon properties.


Step 3: Click on browse. Select image from proper package.


How to set image in non IDE code?
 IDE handles the basic properties of object but if you are working on some other editor that don't provide check the below code to set the image for that object.

// jButton1 is my object so change it to yours and also change the path of image in getResource("path_to_image");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Redo.gif")));

Subscribe on social media for more stuffs.
Related Articles:
[How to create .jar file in netbeans? : http://www.javaquery.com/2011/12/how-to-create-jar-file-in-netbeans.html]
[How to Open file by double clicking on it in our .jar file? : http://www.javaquery.com/2010/12/how-to-open-file-by-double-clicking-on.html]
[How to get .java file from .class file? : http://www.javaquery.com/2011/08/how-to-get-java-file-from-class-file.html]

Understanding basics of jTabbedPane

This tutorial for beginners. I'll help you to understand the basics of jTabbedPane. We'll understand the below topics in this tutorial.

  • How to add new tab in jTabbedPane? or How to add new tab in java swing?
  • How to remove tab from jTabbedPane? or How to remove tab in java swing?
  • How to set popup menu in jTabbedPane? or How to set icon in popup menu item?

jTabbedPane , swing

If you are working with IDE like netbeans then it provides drag and drop facilities for components. All you need to implement code for new tab. Lets have a look at code snippet.
/*
 * New Tab 
 * Code for non IDE environment 
 */
JTabbedPane jTabbedPane1 = new JTabbedPane();
JPanel content = new JPanel();
setContentPane(content);
content.setLayout(new BorderLayout());
content.add(jTabbedPane1);

/* 
 * Code for IDE environment and non IDE enviroment 
 * Add this line of code for button click event, key stroke event, etc...
 * Below code insert jTextArea in every new tab. You can insert component as per your need.
 * jTabbedPane1.addTab("Untitled",new JScrollPane(new JTextArea());
*/
jTabbedPane1.addTab("Untitled", new JScrollPane());

Now lets check out the code for closing the tab. I think there no need to say that jTabbedPane must be initialized.
/* 
 * Remove tab / Close tab
 * Add this line of code for button click event, key stroke event, etc... 
 */
int remIndex = jTabbedPane1.getSelectedIndex();
if (remIndex < 0) {
     JOptionPane.showMessageDialog(rootPane, "No tab available to close");
} else {
     jTabbedPane1.remove(remIndex);
}

Let's create popup menu on the tab. I'm giving you the basic idea for creating popup menu. You need to implement click event for that popup menu items. In below code snippet you can also find how to set icon in popup menuitems.

How to implement click event on popup menuitems?
- You can attach action listener for that menu items.
 /* 
  * Popup menu
  * images/icons for popup menuitems are available in package com.javaquery.images
  * Add this code in constructor 
 */
 JPopupMenu pop_up = new JPopupMenu();
 JMenuItem savefile = new JMenuItem("Save");
 savefile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Save.gif")));
 JMenuItem openfile = new JMenuItem("Open File");
 openfile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Open.gif")));
 JMenuItem newtab = new JMenuItem("New Tab");
 JMenuItem closetab = new JMenuItem("Close Tab");

 //savefile.setAccelerator(KeyStroke.getKeyStroke("control S")); //Key stroke
 //savefile.addActionListener(new savefile()); //new savefile() is class the implements actionlistner

 pop_up.add(savefile);
 pop_up.add(openfile);
 pop_up.addSeparator();
 pop_up.add(newtab);
 pop_up.add(closetab);
 jTabbedPane1.setComponentPopupMenu(pop_up);

How to implement Cut, Copy, Paste, Undo, Redo in java swing?

I was exploring the folders and found my college project. I thought let me write article for old school project. It might help students working for first time in java swing. Its very easy to implement Cut, Copy, Paste, Undo, Redo when you deal with text input(s).

Cut, Copy, Paste, Undo, Redo in java swing

I took jTextarea in this example. I'll give you core script but you have to modify the code as per your need. Like onclick event, KeyStroke, etc...

Code for handling cut event
 /* Below code for netbeans */ 
 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextArea1.cut();
 }

 /* Below code when you want to attach action listener */
 class cut implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            jTextArea1.cut();
        }
 }

Code for handling copy event
 /* Below code for netbeans */ 
 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextArea1.copy();
 }

 /* Below code when you want to attach action listener */
 class copy implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            jTextArea1.copy();
        }
 }

Code for handling paste event
 /* Below code for netbeans */ 
 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextArea1.paste();
 }

 /* Below code when you want to attach action listener */
 class paste implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            jTextArea1.paste();
        }
 }

To implement Undo and Redo you have to run code with in constructor. Below code will implement UndoableEditListener for jTextarea.
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager;

/* Create global variable */
UndoManager undo = new UndoManager();

jTextArea1.getDocument().addUndoableEditListener(
                new UndoableEditListener() {
                    public void undoableEditHappened(UndoableEditEvent e) {
                        undo.addEdit(e.getEdit());
                }
});

Code for handling undo event
 /* Below code for netbeans */ 
 private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            undo.undo();
        } catch (CannotRedoException cre) {
            cre.printStackTrace();
        }
 }

 /* Below code when you want to attach action listener */
 class undo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
               undo.undo();
            } catch (CannotRedoException cre) {
               cre.printStackTrace();
            }
        }
 }

Code for handling redo event
 /* Below code for netbeans */ 
 private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            undo.redo();
        } catch (CannotRedoException cre) {
            cre.printStackTrace();
        }
 }

 /* Below code when you want to attach action listener */
 class redo implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            try {
               undo.redo();
            } catch (CannotRedoException cre) {
               cre.printStackTrace();
            }
        }
 }

Source Code

JComboBox (javax.swing.JComboBox) Explained

I generally work around web application. I didn't have much idea about desktop application in Java. I got client wants to create Inventory Management application. I found that its little bit hard to deal with the JComboBox when work around dynamic data. Let me show you how you can hide some of data (i.e database ID, Description, etc...) related to selected item.


Step 1. How to load data in JComboBox when form open or load or called from other class?
Use the function  private void formWindowOpened(java.awt.event.WindowEvent evt). I'll give you code snippet that'll help you to understand in better way.
private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        Vector comboBoxItems = new Vector();
        boolean productCount = true;
        String itemID = "", name = "", manufacturer = "", stock = "";
        try {
            Connection con = variables.getDatabaseConnection();
            PreparedStatement product_stmt = con.prepareStatement("select * from warehouse");
            ResultSet product_rs = product_stmt.executeQuery();
            comboBoxItems.add(new Item(0, "Select Item"));
            while (product_rs.next()) {
                productCount = false;
                itemID = product_rs.getString("idwarehouse");
                name = product_rs.getString("NameOfProduct");
                // To understand below code please read the question 2 in this article
                comboBoxItems.add(new Item(Integer.parseInt(itemID), name));
            }
            if (productCount) {
                comboBoxItems.add(new Item(0, "No Item Available"));
            }
            con.close();
            final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
            jComboBox1.setModel(model);
            jComboBox1.addActionListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
}
Step 2. How to bind the data within JComboBox?
To bind the data for each item we use the below function. That'll also help us to retrieve the data when value of JComboBox is changed or say action performed.
class Item {
        private int id;
        private String description;

        public Item(int id, String description) {
            this.id = id;
            this.description = description;
        }

        public int getId() {
            return id;
        }

        public String getDescription() {
            return description;
        }

        public String toString() {
            return description;
        }
}
Step 3. How to handle event on JComboBox?
Implement the ActionListener for the current class (i.e java file, form, etc...). Modify the line public class name_of_file extends javax.swing.JFrame to public class productStock extends javax.swing.JFrame implements ActionListener. As you are Overriding the ActionListener you have to add that function like below.
@Override
public void actionPerformed(ActionEvent e){
//implement code
}

Now let me show you code snippet that demonstrate the action of change value in JComboBox.
@Override
public void actionPerformed(ActionEvent e) {
/*
* If you are performing action listener for other component then use below code
* if(e.getSource()==jComboBox1){
* Put the below code within IF box          
* }
*/
        jComboBox1 = (JComboBox) e.getSource();
        Item item = (Item) jComboBox1.getSelectedItem();
        //Implement your code here
        System.out.println("Database ID of selected value"+String.valueOf(item.getId()));
        try {
            Connection con = variables.getDatabaseConnection();
            PreparedStatement warehouse_stmt = con.prepareStatement("select * from warehouse where(idwarehouse=?) limit 0,1");
            warehouse_stmt.setString(1, String.valueOf(item.getId()));
            ResultSet warehouse_rs = warehouse_stmt.executeQuery();
            if (warehouse_rs.next()) {
                jTextField1.setText(warehouse_rs.getString("NameOfProduct"));
            } else {
                JOptionPane.showMessageDialog(rootPane, "Select proper item");
            }
            con.close();
        } catch (Exception exp) {
            JOptionPane.showMessageDialog(rootPane, exp.getMessage());
        }
}     
You have to add all this 3 code in your file in order to work.
  1. It'll load data when window opened (note: If you want it to load on other action use the code with in function. [i.e : On click, On focus, etc...]).
  2. It'll bind data in JComboBox.
  3. It'll handle the change event of JComboBox.

How to put image in jFrame or Swing application?

            I've got so many requests on my website that how to put image in swing application or Jframe. Its very easy for one to understand. I hope you are using some IDE for creating swing application. I'm using Netbeans here to create one.

To place image on swing application you can use jLabel for that. If you are not using any IDE here is code for you.

private javax.swing.JLabel jLabel1;
jLabel1 = new javax.swing.JLabel();
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon_128.png")));
//Here image placed in package/folder called images. For better explanation read the whole article.

Now lets roll to IDE Netbeans. Netbeans implement same as above i wrote.

Step 1 : Create package/folder in project that contains images for your project.
  • Why is required so? : Say if you are building application for your client that requires images in that. Pointing image out of project folder will not be available in client's computer. So by placing/binding images within project will always available in *.jar file.

Step 2 : Create or place jLable in jFrame. 


Step 3 : Open up jLabel properties and browse icon.

properties jLabel

Step 4 : Select desired image either way from package (Recommended) or external image.

swing, netbeans

Step 5 : Press "Ok" and  now remove text of jLabel.

jLabel

Output : Finally we've done it. You can move your image at your desired place.



How to pass variable values between Jframes in NetBeans?

java swing JFrame Pass Values

This article stands in front of my all other articles. I got so many request to update its content for better user experience so here I am.

Swing
Swing is built on base of Abstract Window Toolkit (AWT). In other words swing is extended version of AWT for better and richer user interface. Its used to create desktop applications like chat, accounting and so on.

I'll also demonstrate how you can pass values to same JFrame without opening new JFrame.
Read more How to get list of opened JFrame in Java Swing?
Read more Sample Client - Server Chat Application in Java

Creating ParentJFrame with following components.
  • Text Field to type message
  • Button to send message

ParentJFrame Source Code
Look for the btnSendActionPerformed(java.awt.event.ActionEvent evt) method.
/* This example is coded in NetBeans so you'll find some IDE generated code unexplained. */
package com.javaquery.swing;

import java.awt.Frame;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ParentJFrame extends javax.swing.JFrame {

    public ParentJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                      
    private void initComponents() {
        lblInfo = new javax.swing.JLabel();
        textField = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Parent JFrame");

        lblInfo.setText("Message");

        btnSend.setText("Send Message");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSend)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblInfo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(textField, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblInfo)
                    .addComponent(textField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnSend)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }                        

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {                                        
        /* Get text from TextField */
        String message = textField.getText();
        String setNewMessage = "";
        boolean isFrameOpen = false;

        if (message != null && message.length() > 0) {
            /**
             * Get list of opened JFrames 
             * Read more about "How to get list of opened JFrame in Java Swing?"
             * http://www.javaquery.com/2014/06/how-to-get-list-of-opened-jframe-in.html
             */
            for (Frame frame : Frame.getFrames()) {
                /* Match title of JFrame */
                if (frame.getTitle().equals("Child JFrame")) {
                    /* Cast to ChildJFrame */
                    ChildJFrame childJFrame = (ChildJFrame) frame;
                    /**
                     * Access TextArea of ChildJFrame using getter method. 
                     * You can so same for other component like JLabel, Buttons,
                     * Combobox, List by creating getter and setter method.
                     */
                    String getPreviousMessages = childJFrame.getTextArea().getText();
                    if (getPreviousMessages.length() > 0) {
                        /* Append new message to String */
                        setNewMessage = getPreviousMessages + "\n[" + new Date().toString() + "]: " + message;
                    } else {
                        /* Create new message String */
                        setNewMessage = "[" + new Date().toString() + "]: " + message;
                    }

                    /* Set value of TextArea */
                    childJFrame.getTextArea().setText(setNewMessage);
                    isFrameOpen = true;
                }
            }

            /* If ChildJFrame is not opened yet */
            if (!isFrameOpen) {
                /* Create new message String */
                setNewMessage = "[" + new Date().toString() + "]: " + message;
                /* Create an object of ChildJFrame */
                ChildJFrame childJFrame = new ChildJFrame();
                /* Set message in TextArea */
                childJFrame.getTextArea().setText(setNewMessage);
                /* Make ChildJFrame visible */
                childJFrame.setVisible(true);
            }
        } else {
            /* Alert box when user try to send blank message */
            JOptionPane.showMessageDialog(null, "Type something to send");
        }
    }                                       

    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                /**
                 * Read more about "How to apply/set up swing look and feel?"
                 * http://www.javaquery.com/2013/06/how-to-applyset-up-swing-look-and-feel.html
                 */
                try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(LookAndFeel.class.getName()).log(Level.SEVERE, null, ex);
                }
                new ParentJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnSend;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JTextField textField;
    // End of variables declaration                   
}

Creating ChildJFrame with following components.
  • Text Area (Create Getter and Setter method)
ChildJFrame is aimed to receive messages so there ain't much coding.


ChildJFrame  Source Code:
/* This example is coded in NetBeans so you'll find some IDE generated code unexplained. */
package com.javaquery.swing;

public class ChildJFrame extends javax.swing.JFrame {
    public ChildJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        scrollPane = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        lblInfo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Child JFrame");

        textArea.setColumns(20);
        textArea.setRows(5);
        scrollPane.setViewportView(textArea);

        lblInfo.setText("Message Received");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblInfo)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lblInfo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChildJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JLabel lblInfo;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTextArea textArea;
    // End of variables declaration                   

    /**
     * Getter Method
     * @return the textArea
     */
    public javax.swing.JTextArea getTextArea() {
        return textArea;
    }

    /**
     * Setter Method
     * @param textArea the textArea to set
     */
    public void setTextArea(javax.swing.JTextArea textArea) {
        this.textArea = textArea;
    }
}

I created getter and setter method to access TextArea of ChildJFrame. To access Label, Button, Combobox, etc... Create your getter and setter method.


[Updated: 01/06/2013] How to update jtable dynamically from Oracle , MySQL (Database)?

Once i found updating jTable dynamically was tough task. Now I'll help you to understand that code. I'm considering that you are working in Integrated Development Environment. Don't waste your time by coding your project in text editor like notepad or so.

jTable
jTable

I'm considering that you already declared jTable in your code. I'm updating the jTable data on formWindowOpened. You can set your own event for the code below.

// import database class as per oracle and mysql selection.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
        Object[][] rowData = new Object[2][2];
        Object columnNames[] = {"Client ID", "Client Name"};
        int i = 0;
        try {
            /*
             * It's my own function to load database connection.
             * You have to load database driver and connection.
             * public static final Connection getDatabaseConnection() throws Exception {
             * Class.forName(dbdriver);
             * return DriverManager.getConnection(dbhost, dbusername, dbpassword);
             * }
             */
            Connection con = variables.getDatabaseConnection(); 
            PreparedStatement client_stmt = con.prepareStatement("select idclients,ClientName from clients limit 0,2");
            ResultSet client_rs = client_stmt.executeQuery();
            while (client_rs.next()) {
                rowData[i][0] = client_rs.getString("idclients");
                rowData[i][1] = client_rs.getString("ClientName");
                i++;
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        DefaultTableModel tm = new DefaultTableModel(rowData, columnNames);
        jTable1.setModel(tm);       
}

This is it. Choose your event to load the data. Don't forget to change the database query and its column name. Subscribe to Google plus and Facebook for more stuffs...