Imagine you have completed a course on Java and you have created a few “applications” which are command-line. Even if you create the most sophisticated and efficient application, if it doesn’t have a good user interface — users won't appreciate it.
Now you have realized that User Interface — to be specific a GUI: Graphical User Interface is what you want. You looked at the most common technologies used and decided that you can only make it web-based since you don’t know other technologies to make a native app. But if I say you can use Java to create an app that will run on almost any operating system, would you believe me?
I’m not a psychic so I don't know what you replied, but the answer is yes. We can use SWING to achieve this purpose. Java Swing is platform-independent and lightweight; which means it is both developer-friendly and user-friendly.
But wait, what about this other thing you read on the internet or taking a course called Java AWT which is arguably more popular than Swing?
If you had read more about AWT, you would know that it is Platform Dependent, heavyweight, and doesn’t even follow the MVC architecture.
The only complaint you may have is that Swing has an imperative syntax but we can manage.
Before I learn anything related to programming, I like to start with a starter program — a simple program that helps you start with the programming language, library, or anything you want to learn.
Hierarchy
Swing Starter Program
Here we have used two classes — JFrame and JButton.
- JFrame: JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.
- JButton: JButton is a component which is used to create a labeled button that can result in some action (or rather — execute some code) when it is pressed.
We have used four functions in JFrame till now. These are:
public void setSize(int width, int height);
This is a method inherited from java.awt.Window and it sets width and height of the frame.public void setLayout(LayoutManager mgr);
This is a method inherited from java.awt.Container and it sets the layout manager for the frame/container.public void setVisible(boolean b);
This method is used to either show or hide the frame.public Component add(Component comp);
This method is inherited from java.awt.Container used to add a component to the frame.
Try running this code in your project. One reminder for Eclipse users, you would probably have to include this in your module descriptor file (module-info.java):
requires java.Desktop;
Thank you for reading. I will publish more on this soon — follow me: Tejas M R to not miss them.