javaprogrammer javaprogrammer - 1 year ago 66
Java Question

Why is JButton opening an empty frame instead of calling PMotion class?

I have two java files (classes) and has a button. When I press that button, I want it to dispose the current frame and go to the class. As you can see in the file, I have

new PMotion().setVisible(true);

The frame.dispose(); works, as it closes But instead of opening, it just opens a blank JFrame. Please note: I only copied the relevant code from - in reality, it is a fully working application. Help is appreciated!

import java.awt.EventQueue;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JSeparator;
import javax.swing.JScrollBar;

public class PMotion extends JFrame {

private JFrame frame;

* Launch the application.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PMotion window = new PMotion();

} catch (Exception e) {

* Create the application.
public PMotion() {

* Initialize the contents of the frame.
private void initialize() {
frame = new JFrame("Projectile Motion");
frame.setBounds(100, 100, 800, 600);

JButton btnProjectile = new JButton("Projectile");
btnProjectile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new PMotion().setVisible(true);

btnProjectile.setBounds(260, 137, 117, 29);

Answer Source

Why does your class extend JFrame and then in the constructor create a new JFrame?

You either:

  1. extend JFrame (which is not a good idea), or
  2. create a new JFrame(...)

but you don't do both.

//frame = new JFrame("Projectile Motion");
frame = this;

In your case you could just use the code from above, since PMotion is a JFrame already.