Skip to content
Advertisement

JFrame ending in some time

Whenever I run my code it ends in a few seconds. Why?

This is the Main file:

public class Main {
    public static void main(String[] args) {
        System.out.println("This is running");
        GameWin Win = new GameWin();
    }
}

This is the GameWin file:

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

public class GameWin implements ActionListener{

JFrame frame = new JFrame();
JButton myButton = new JButton("New Window");

public void GameWin(){

    myButton.setBounds(100,160,200,40);
    myButton.setFocusable(false);
    myButton.addActionListener(this);

    frame.add(myButton);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(420,420);
    frame.setLayout(null);
    frame.setVisible(true);

}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource()==myButton) {
        frame.dispose();
    }
}
}

When I try to run this code it shows running and then the code ends with exit code 1 which is good, but it just ends without showing the window. Is there something wrong with my JRE or JDK?

Advertisement

Answer

  1. Constructors do not have return type. public void GameWin() is not a constructor, thus the default constructor is called that does nothing interesting here. It should be declared public GameWin().

  2. You must call any Swing-related function in the Swing-main-thread for consistency. Thus call the construction of the GameWin object through SwingUtilities class. Even if it seems to work without such, it may not in different kind of environnements.

Hence:

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

public class GameWin implements ActionListener{

  public static void main(String[] args) {
    System.out.println("This is running");
    SwingUtilities.invokeLater(() -> new GameWin());
  }
  
  JFrame frame = new JFrame();
  JButton myButton = new JButton("New Window");

  public GameWin(){               
    myButton.setBounds(100,160,200,40);
    myButton.setFocusable(false);
    myButton.addActionListener(this);   
    frame.getContentPane().add(myButton);   
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(420,420);
    frame.setLayout(null);
    frame.setVisible(true);   
  }

  @Override
  public void actionPerformed(ActionEvent e) {
    if(e.getSource()==myButton) {
      frame.dispose();          
    }       
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement