Martyn Martyn - 1 year ago 63
Java Question

Why is my JPanel empty after button is clicked?

I'm learning how to create event listeners in Java for a button click. I want a panel to popup with form items. I've built the panel in the action listener's contructor, but it's empty when it opens. I thought it makes sense to only build this one, then just show it when the button is clicked (actionPerformed). Obviously not :)

Below is my ActionListener class:

package biz.martyn.budget;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class NewTransaction implements ActionListener {

protected JPanel panel = new JPanel(new GridLayout(0, 1));

public void NewTransaction() {
String [] category = {"Internet", "Clothes", "Rent", "Salary", "Groceries"};
JComboBox combo = new JComboBox(category);


panel.add(new JLabel("Description:"));
JTextField desc = new JTextField();

panel.add(new JLabel("Date:"));
JTextField date = new JTextField();

panel.add(new JLabel("Amount:"));
JTextField amount = new JTextField();

public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.showConfirmDialog(null, panel, "New transaction",

Here is how I'm attaching the event:

JButton newTransactionButton = new JButton("New transaction");
newTransactionButton.addActionListener(new NewTransaction());

I'd appreciate any additional advice on conventions when doing this sort of thing coz I'm quite the beginner, thanks.

Answer Source

I've built the panel in the action listener's contructor, but it's empty when it opens

The following...

public void NewTransaction() { a method, not a Constructor. You need to explicitly call it, or change it to a constructor

public NewTransaction() {