Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


JFrame Close Button

JFrame Close Button

JFrame Close Button

Hi, I am new to Java. Better yet I'm new to programming PERIOD.

I have to write my Hello World program for my class and have it exit with an "Exit" button.

I cannot get it to work properly.

Can someone please help!!!!

This is what I have. It runs smoothly just cannot figure out how to add the button.

import javax.swing.*;

public class HelloWorldGUI


private static void createAndShowGUI() {

JFrame frame = new JFrame("");


JLabel label = new JLabel("Hello World!!!");





public static void main(String[] args) {



RE: JFrame Close Button


That is simple : add a JButton which listens for ActionEvents handled by your class, ( for this your class will have to implement ActionListener, ) then in actionPerformed() method you just dispatch a WINDOW_CLOSING event.

If you want to keep the current JLabel too, add a layout manager of your choice which will make possible arranging multiple widgets the way you want.

CODE --> HelloWorldGUI.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloWorldGUI implements ActionListener {
    JFrame frame;

    private void createAndShowGUI()
        JLabel label = new JLabel("Hello World!!!");
        JButton button = new JButton("Run, Forrest, run !!!");


        frame = new JFrame("");
        frame.setContentPane(new JPanel(new FlowLayout()));



    public void actionPerformed(ActionEvent e)
        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

    public static void main(String[] args)
        new HelloWorldGUI().createAndShowGUI();



Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close