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.