-1

Hello I am making a windows app using my java code but I am having trouble with swing GUI. Eventually I am trying to make a Panel that comes up and has a few options for different reports you can run. For now, I am just trying to get my panel to pop up and a button with an alert. Here is my code. Since this is intellij IDEA, there's not really any code for the GUI but it is in a .form file. I want to add an event listener on JButton button that says hi.The error I get is null pointer execption. What am I doing wrong? Thanks in Advance.

package com.project.go;

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

/**
 * Created by Joe on 12/16/2016.
 */
public class App {
private JButton button;
private JPanel panelMain;
private JTextPane MenuWelcome;
private JComboBox pullDownBox;
private JButton Exit;
private JTextArea DateField;

public static void main(String[] args) {
    JButton button = new JButton("run");
    JFrame frame = new JFrame("App");
    frame.setContentPane(new App().panelMain);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    new App();

}

public App() {
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "hi");
        }
    });
}

private void createUIComponents() {
    // TODO: place custom component creation code here
}
}
Joeysk
  • 5
  • 4
  • using a debugger should resolve this issue in no time. In short: be careful what you rely on. The IntelliJ forms plugin can be quite evil. –  Dec 20 '16 at 00:24

1 Answers1

2

The problem is you are calling instance of panelMain which you didnt create any:

frame.setContentPane(new App().panelMain);

You need to first instantiate:

private JPanel panelMain;

Maybe you might want to use encapsulation which I belive would be good practice.

HRgiger
  • 2,750
  • 26
  • 37