Here in this tutorial we will build a simple GUI (graphical user interface) application for a simple client version of a chat program. To do that, we need to use Java’s
swing library. We are going to use
GroupLayout class to manage sizing and position of the
Buttons,
TextFields,
Labels and
ScrollPanes etc.
A captured image of the sample GUI:
How it works?User has to type his/her name in order to send a message. Doing that he can send message to the console. After sending a message or creating a username, There will be a status update in south left corner of the frame.
User Interface StructurePlease note that this is only the graphical interface to manage Chat of a client. Network functionality is not added. Meaning that it can’t connect to a socket and receive other clients messages.
Horizontal Group Configurationlayout.setHorizontalGroup(layout
.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane)
.addComponent(statusbar)
.addGroup(layout.createSequentialGroup()
.addComponent(label)
.addComponent(username)
.addComponent(setusernamebutton)
.addGroup(layout.createSequentialGroup()
.addComponent(message)
.addComponent(sendbutton));
Vertical Group Configurationlayout.setVerticalGroup(layout.createSequentialGroup()
.createSequentialGroup()
.addComponent(jScrollPane)
.addComponent(statusbar)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(label).addComponent(username).addComponent(setusernamebutton))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(message).addComponent(sendbutton)) );
For more info on layouts, please visit the following links below:
https://docs.oracle.com/javase/tutorial/uiswing/layout/group.htmlhttp://docs.oracle.com/javase/7/docs/api/javax/swing/GroupLayout.html Here is the code of this GUI application:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
/**
* Created by ismailsirma on 25.6.2015.
*/
public class ClientSwing {
JTextField username;
JTextField message;
JLabel label1;
JScrollPane jScrollPane1;
JLabel statusbar;
JButton button1;
JButton button2;
JTextArea textArea;
JFrame frame;
String usernamee = null;
Date date = new Date();
final static Color ERROR_COLOR = Color.RED;
ClientSwing(){
// Create a frame
frame = new JFrame("Chat Client");
frame.setSize(500, 400);
// create a text field for user to enter their name
username = new JTextField();
// create a text field for user to enter their message
message = new JTextField();
// text area where incoming and outgoing messages being seen
textArea = new JTextArea();
button1 = new JButton("Set nickname");
button2 = new JButton("Send");
label1 = new JLabel();
statusbar = new JLabel();
// How frame is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Chat Client");
textArea.setColumns(20);
textArea.setRows(5);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
jScrollPane1 = new JScrollPane(textArea);
label1.setText("Enter your username:");
// creates the graphical user interface
SetLayout(frame, label1, username, message, statusbar, button1, button2, jScrollPane1);
// set the frame visible
frame.setVisible(true);
// when user hits enter key in username field, show it on status bar
username.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
usernamee = username.getText();
statusbar.setText("Username set!");
username.setEnabled(false);
frame.setVisible(true);
}
});
// when an action is performed, capture the action
// button1 is the button sets the username
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
usernamee = username.getText();
statusbar.setText("Username set!");
username.setEnabled(false);
frame.setVisible(true);
}
});
message.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (usernamee == null) {
message.setText("");
// work in progress
}
textArea.append(usernamee + ": " + message.getText() + "\\n");
//clear the message area
message.setText("");
//clear the status area
statusbar.setText("");
username.setEnabled(false);
frame.setVisible(true);
}
});
// button2 is the button sends the message
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// take the text and put it on the label
// if user didn't specify the user name
if(usernamee == null){
message.setText("");
// work in progress
}
textArea.append(usernamee + ": " + message.getText() + "\\n");
//clear the message area
message.setText("");
//clear the status area
date = new Date();
statusbar.setText("Your message at " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + " has been sent");
username.setEnabled(false);
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ClientSwing();
}
});
}
public void SetLayout(JFrame frame,JLabel label, JTextField username, JTextField message, JLabel statusbar, JButton setusername, JButton send, JScrollPane jScrollPane){
// Creating layout
GroupLayout layout = new GroupLayout(frame.getContentPane());
frame.getContentPane().setLayout(layout);
//Create a parallel group for the horizontal axis
GroupLayout.ParallelGroup hGroup = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
//Create a sequential and a parallel groups
GroupLayout.SequentialGroup h1 = layout.createSequentialGroup();
GroupLayout.ParallelGroup h2 = layout.createParallelGroup(GroupLayout.Alignment.TRAILING);
//Add a container gap to the sequential group h1
h1.addContainerGap();
//Add a scroll pane and a label to the parallel group h2
h2.addComponent(jScrollPane, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
h2.addComponent(statusbar, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
//Create a sequential group h3
GroupLayout.SequentialGroup h3 = layout.createSequentialGroup();
h3.addComponent(label, 0, GroupLayout.DEFAULT_SIZE, 150);
h3.addComponent(username, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
h3.addComponent(setusername, 0, GroupLayout.DEFAULT_SIZE, 120);
// new added
GroupLayout.SequentialGroup h4 = layout.createSequentialGroup();
h4.addComponent(message, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
h4.addComponent(send, 0, GroupLayout.DEFAULT_SIZE, 120);
hGroup.addGroup(h4);
//Add the group h3 to the group h2
hGroup.addGroup(h3);
//Add the group h2 to the group h1
hGroup.addGroup(h2);
h1.addContainerGap();
//Add the group h1 to the hGroup
hGroup.addGroup(GroupLayout.Alignment.TRAILING, h1);
//Create the horizontal group
layout.setHorizontalGroup(hGroup);
//Create a parallel group for the vertical axis
GroupLayout.ParallelGroup vGroup = layout.createParallelGroup();
//Create a sequential group v1
GroupLayout.SequentialGroup v1 = layout.createSequentialGroup();
//Add a container gap to the sequential group v1
v1.addContainerGap();
//Create a parallel group v3
GroupLayout.ParallelGroup v3 = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
v3.addComponent(label);
v3.addComponent(username);
v3.addComponent(setusername);
//Create a parallel group v2
GroupLayout.ParallelGroup v2 = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
v2.addComponent(message,0,70,300);
v2.addComponent(send);
//Add the group v2 tp the group v1
v1.addGroup(v3);
v1.addGroup(v2);
v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
v1.addComponent(jScrollPane, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
v1.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED);
v1.addComponent(statusbar);
v1.addContainerGap();
//Add the group v1 to the group vGroup
vGroup.addGroup(v1);
//Create the vertical group
layout.setVerticalGroup(vGroup);
//Window to be sized to fit the preferred size and layouts of its sub components.
//The resulting width and height of the window are automatically enlarged if either of dimensions
//is less than the minimum size as specified by the previous call to the setMinimumSize method.
frame.pack();
}
}
Author
İsmail Erdem Sırma
Senior Software Engineer