GUI

Introduction

Main.java
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("My Title");
        frame.setResizable(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel label = new JLabel("Hello, World!");
        frame.add(label);
        frame.pack();
        frame.setVisible(true);
    }
}

Corrected Java Swing Example

The following Java program creates a simple graphical application using Swing. This application displays a window with the title "My Title" and includes a label saying "Hello, World!".

Key Components:

  • JFrame: The main window.

  • JLabel: Displays text within the window.

  • setTitle(): Sets the window title.

  • setSize(): Defines the window dimensions.

  • setResizable(): Allows the window to be resized by the user.

  • setDefaultCloseOperation(): Determines the close operation of the frame

To set a window's icon in a Java application, first create an ImageIcon object with the desired image file and then use the setIconImage method:

Replace "filename" with the path to your image file.

Java GUI Example

This example demonstrates a basic Java GUI application using a custom frame called MyFrame which extends JFrame.

Main.java

MyFrame.java

Key Components:

  • Title: Sets the window title to "My Title".

  • Size: Window dimensions set to 500x500 pixels.

  • Resizable: Allows users to resize the window.

  • Close Operation: Exits the application on closing the window.

  • Label: Displays "Hello, World!" in the window.

Note:

Ensure javax.swing is imported for JFrame and

The following code snippets demonstrate how to change the background color of a GUI component using Java:

  1. Set the background to red:

  2. Set the background to green using RGB values:

  3. Set the background to white using a hexadecimal value:

In the example code, a component on a frame has its layout set to null, allowing for absolute positioning. The setBounds method is missing a component identifier. To correct the code, include the component's name before setBounds. For example, if the component is a button, the corrected line would be:

Ensure to replace button with the actual component variable name you are using.

Last updated