Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an hello world in Java Swing? What is wrong in my code?

Tags:

java

swing

I am studying Java Swing and I have some problem with the following simple code:

package com.techub.exeute;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;


public class Main{

    public static void main(String[] args) {

        JFrame frame = new JFrame("FrameDemo");
        frame.setMinimumSize(new Dimension(800, 400));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER);
        myLabel.setFont(new Font("Serif", Font.BOLD, 22));
        myLabel.setBackground(Color.blue);
        myLabel.setOpaque(true);
        myLabel.setPreferredSize(new Dimension(100, 80));

        frame.getContentPane().add(myLabel, BorderLayout.NORTH);

    }
}

My idea is to create a JFrame object and insert into it an Hello World JLabel object settings some property.

I do it into the main() method. The problem is that when I execute the program I don't see anything !!! Why? What is wrong in my code?

Tnx

Andrea

like image 873
AndreaNobili Avatar asked Feb 13 '26 11:02

AndreaNobili


1 Answers

You are creating the frame but you are not displaying it. Call

frame.setVisible(true);

to display it.

Another thing: you should not manipulate GUI components in the main thread. Instead, create a new method for creating the frame and setting up the components, and run that method in the event dispatch thread, like in the example from the official tutorial:

import javax.swing.*;        

public class HelloWorldSwing {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
like image 71
Joni Avatar answered Feb 15 '26 00:02

Joni