Learning Java GUI for making some apps nice!! And actually working on a chat app! POG!!

Cybear Tron's photo
Cybear Tron

Published on Jul 31, 2021

7 min read

Hwlo There people!!!

I am like learning some Java gui.. I have done it in python using Tkinter but now is the time for Java and Swing.

And later we will actually start some work on a chat app!!!

So I guess you guys can also find this helpful and fun!! POGGERS!!!!

So before we start I have to tell some fundamentals of GUI.

The Main parts of the GUI are:

Parts of a GUI.png

A frame, or group box, is a type of box within which a collection of graphical control elements can be grouped as a way to show relationships visually, either because the items are functionally related (such as a radio button), or because they apply to related objects. ~Wikipedia

Its like the fundamental of all guis. Its the fundamental window that is on a GUI on which other components of a gui are based on. There are much more components of a gui rather than jus those that are marked in the image. Like Scroll Bars, Ribbons etc.

image.png

The first thing one should do in gui development is to make a container and make it visible. Thats what I first did after importing the awt and swing packages.

But we have other forms of containers too in java. Not jus a frame.. A frame is the basic form of a container.

Container classes are classes that can have other components on it. So for creating a Java Swing GUI, we need at least one container object. There are 3 types of Java Swing containers. ~Guru 99

Ok So I created a little window... A bad one:

import javax.swing.*;
import java.awt.*;

public class Jabba{
    public static void main(String[] args) {
        JFrame main = new JFrame("Hwlo");
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setSize(1024,768);
        JButton hwlobut= new JButton("Hwlo??");

        main.getContentPane().add(hwlobut);

        main.setVisible(true);
    }
}

image.png

Ok So I decided to revert back to Vscode from JLite as it is getting harder and harder for me to work with it... Cuz it doesn't have a nice intellisense, keyboard shortcuts and damn no Dark mode....

I am very well versed with vscode and it actually is usable... Not insulting JLite... But it still has so many features left to be developed to be good....

Ok So adding another button jus overlaps... So we gotta use some layouts and also some other container classes!!!

Ok So using Guru99's Tutorial had one thing done:

image.png

I am now gonna try actually making it functional!! First I searched how to add functionality to buttons and soon I will first let it send the messages to the main text area.. Btw the code for this is:

//We need to import both the swing and awt packages cuz we will use some things from the latter too.
import javax.swing.*;
import java.awt.*;
class Jabba {
    public static void main(String args[]) {

        //The main frame and here we also set its size. 
        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        //The menu bar that will be there for joining and creating rooms for chatting and a help one
        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("Connect");
        JMenu m2 = new JMenu("Help");
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Create new room");
        JMenuItem m22 = new JMenuItem("Join an Existing Room");
        m1.add(m11);
        m1.add(m22);

        //Our Main Panel in which there is a label and the two buttons for sending and resetting.
        JPanel panel = new JPanel();
        JLabel label = new JLabel("Enter Text");
        JTextField tf = new JTextField(10);
        JButton send = new JButton("Send");
        JButton reset = new JButton("Reset");
        panel.add(label); 
        panel.add(tf);
        panel.add(send);
        panel.add(reset);

      //Our Text Area where the messages need to go!!
        JTextArea ta = new JTextArea();

        //jus adding everything to the main frame
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
       //The Borderlayout which lets us to set up a layout, is from the awt package so you now know 
          //why we needed it...  The .SOUTH and and the other directions are for laying them out lol
        frame.getContentPane().add(BorderLayout.NORTH, mb);
        frame.getContentPane().add(BorderLayout.CENTER, ta);
        frame.setVisible(true);
    }
}

Ok So I added this functionality to our send button to jus add a "Hwlo" in the text area in a new line... I need to add the actual message.. For that add this code snippet jus below where we have declared the textarea ta.

send.addActionListener(e ->
            {
                ta.append("Hwlo "+"\n");
               //Maybe some other code you know hehe...
            });

Before getting the message that is on our textfield, we need to add two scroll bars...

Ok So I did two things... Added our textarea in a scroll pane so that we can scroll it when it exceeds and also added a function to our reset button.

Image from Gyazo So this is how it works currently.. It doesn't take any input from the text field... So I had added some changes near the text area only... So the current code is:


import javax.swing.*;
import java.awt.*;
class Jabba {
    public static void main(String args[]) {


        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);


        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("Connect");
        JMenu m2 = new JMenu("Help");
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Create new room");
        JMenuItem m22 = new JMenuItem("Join an Existing Room");
        m1.add(m11);
        m1.add(m22);


        JPanel panel = new JPanel();
        JLabel label = new JLabel("Enter Text");
        JTextField tf = new JTextField(10);
        JButton send = new JButton("Send");



        JButton reset = new JButton("Reset");
        panel.add(label); 
        panel.add(tf);
        panel.add(send);
        panel.add(reset);


        JTextArea ta = new JTextArea();
        JScrollPane sp = new JScrollPane(ta);
        send.addActionListener(e ->{
                ta.append("Hwlo "+"\n");
            });
        reset.addActionListener(e ->{
                ta.setText(null);
        }
        );    
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.getContentPane().add(BorderLayout.NORTH, mb);
        frame.getContentPane().add(BorderLayout.CENTER, sp);
        frame.setVisible(true);
    }
}

Ok So now I want to learn how to store the text field value in a variable so that I can display that in the chat instead of jus spamming hwlo lol!!

Ok So I did a lot of small changes right? So I added some comments in the code and also now the message is stored in a variable when the send button is pressed which gets deleted from the text field once its messaged so that new messages can be typed!!

//Import Unga Bunga
import javax.swing.*;
import java.awt.*;
class Jabba {
    //Class
    public static void main(String args[]) {
    //Main Method
        //main frame
        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        //The Menu that will later allow us to connect and create rooms to join a chat
        JMenuBar mb = new JMenuBar();
        JMenu m1 = new JMenu("Connect");
        JMenu m2 = new JMenu("Help");
        //This is for help
        mb.add(m1);
        mb.add(m2);
        JMenuItem m11 = new JMenuItem("Create new room");
        JMenuItem m22 = new JMenuItem("Join an Existing Room");
        m1.add(m11);
        m1.add(m22);

        //Our panel
        JPanel panel = new JPanel();

        JLabel label = new JLabel("Enter Text");
        //The Message field
        JTextField tf = new JTextField(15);
        //The Sending button
        JButton send = new JButton("Send");


        //The resetting button
        JButton reset = new JButton("Reset");
        //Adding the panel
        panel.add(label); 
        panel.add(tf);
        panel.add(send);
        panel.add(reset);

        //The text area where the messages will go
        JTextArea ta = new JTextArea();
        //Adding it to the Scroll Pane so that It has scrolls
        JScrollPane sp = new JScrollPane(ta);
        //Actionlisteners allow us to listen to the actions that take place with 
        //The Specific components like here when the button is pressed
        send.addActionListener(e ->{
            //It will first store the text of the the text field in a
            //variable called msg
            String msg = tf.getText();    
            //Then Will remove the Text from the field so that new messages can be 
            //sent
            tf.setText(null);
            //Now it will send The message to the message text area
            ta.append(msg+"\n");
            });
        reset.addActionListener(e ->{
            //This is for the reset option
                ta.setText(null);
            //It will jus set all the text of the message area to null
            //i.e. Nothing
        }
        );    
        //adds all the content and components to the main frame.
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.getContentPane().add(BorderLayout.NORTH, mb);
        /*notice the BorderLayout here, it is from the awt package and it 
        is letting us lay the components in a specific layout. 
        Also we have changed the component below after the center to sp
        i.e. it is the scrollpane instead of our textarea to get the Scroll Bars!!*/
        frame.getContentPane().add(BorderLayout.CENTER, sp);
        frame.setVisible(true);
        //Pretty Self-Explanatory
    }
}

I would like you to actually pay attention to the comments if you can't understand what is happening in a certain part of the code :D

Now if I run this code, We can see the following: Image from Gyazo So This works nice!!

I don't want to get start networking today to make it actually functional...

So I guess that is all I will do today... So BYE!!!

And btw its not a chat app yet... It just looks like a chat app which it ain't.. So next day we will actually make it a chat app.

 
Share this