0

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(combo);

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

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

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

    @Override
    public void actionPerformed(ActionEvent arg0) {
        int result = JOptionPane.showConfirmDialog(null, panel, "New transaction",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
    }
}

Here is how I'm attaching the event:

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

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

Martyn
  • 6,031
  • 12
  • 55
  • 121
  • Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Sep 22 '16 at 00:07

1 Answers1

2

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

The following...

public void NewTransaction() {

...is a method, not a Constructor. You need to explicitly call it, or change it to a constructor

public NewTransaction() {
copeg
  • 8,290
  • 19
  • 28