Introduction to Java GUI
What is Java GUI?
Java GUI, or Graphical User Interface, is a type of user interface that allows users to interact with electronic devices through graphical icons and visual indicators rather than text-based interfaces, typed command labels, or text navigation. In Java, GUI programming can be done using Swing and AWT (Abstract Window Toolkit).
AWT vs Swing
Java provides two libraries for creating GUIs - AWT and Swing. AWT was the first GUI toolkit introduced in Java, but it was replaced by Swing because of its richer set of components and more sophisticated GUI tools.
AWT components are heavy-weight, meaning they are dependent on the underlying windowing system. On the other hand, Swing components are light-weight and do not rely on the native system.
Basic Components of Java GUI
Windows: These are the frames where the components like buttons, labels, text fields are added. The
javax.swing.JFrame
class is used to create a window in Java Swing.Panels: Panels are containers that hold and group related components together. The
javax.swing.JPanel
class is used to create a panel.Buttons: Buttons are components that trigger a specific action when clicked. The
javax.swing.JButton
class is used to create a button.Labels: Labels are components used to display short texts or images. The
javax.swing.JLabel
class is used to create a label.Text Fields: Text fields are components that allow users to input a single line of text. The
javax.swing.JTextField
class is used to create a text field.
Creating a Basic Java GUI Program
Let's look at a simple Java Swing program that creates a basic window.
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Java GUI");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this program, we first import the javax.swing.*
package, which contains the necessary classes for creating GUIs.
The main
method is where we create our GUI. We first create a JFrame
object, which represents a window in our GUI. We set the title of the window to "My First Java GUI", set its size to 500x400 pixels, and make it visible.
The line frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ensures that the application will close when the window is closed.
Conclusion
Java GUI programming is a vast topic with a lot of components and aspects to cover. This was just an introductory tutorial to give you a basic understanding of what Java GUI is and how it works. As you delve deeper into Java GUI programming, you will learn about more complex components like tables, lists, scroll panes, menus, and much more.