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:
Set the background to red:
Set the background to green using RGB values:
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.
// Creating a label with text
JLabel label = new JLabel("Hello, World!");
// Setting an image icon
ImageIcon img = new ImageIcon("filepath");
label.setIcon(img);
// Configuring text position
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.TOP);
// Changing text color
label.setForeground(Color.RED);
// Setting font style and size
label.setFont(new Font("MV Boli", Font.PLAIN, 30));
// Adjusting icon-text gap
label.setIconTextGap(100);
// Aligning label vertically and horizontally
label.setVerticalAlignment(JLabel.CENTER);
label.setHorizontalAlignment(JLabel.CENTER);
// Customizing background and border
label.setBackground(Color.BLUE);
label.setOpaque(true);
Border border = BorderFactory.createLineBorder(Color.GREEN);
label.setBorder(border);