I am creating a GUI that asks the user to enter an account balance then click a confirm button. After the button is clicked, it is supposed to display the confirmed balance in the confirmed balance box. However, when I click the button, nothing happens. I tried using the “this” keyword in my addActionListener call, but I cant use it in a static method. How do I get the button to work?
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JFormattedTextField;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.text.NumberFormat;
public class Gui_container extends JFrame implements ActionListener{
private JFormattedTextField Balance_Field;
private JTextField Confirm_Field;
private static void create_GUI() {
GridBagConstraints layout = new GridBagConstraints();
JFrame New_Account = new JFrame("Account");
New_Account.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
New_Account.setLayout(new GridBagLayout());
JPanel Main_Panel = new JPanel(new GridBagLayout());
New_Account.setContentPane(Main_Panel);
JLabel Balance_Label = new JLabel("Enter your Balance:");
layout.gridx = 0;
layout.gridy = 0;
layout.insets = new Insets(10,10,10,10);
Main_Panel.add(Balance_Label, layout);
JFormattedTextField Balance_Field = new JFormattedTextField(NumberFormat.getNumberInstance());
Balance_Field.setColumns(10);
layout.gridx = 1;
layout.gridy = 0;
layout.insets = new Insets(10,10,10,10);
Main_Panel.add(Balance_Field, layout);
JLabel Confirm_Label = new JLabel("Confirmed Balance:");
layout.gridx = 0;
layout.gridy = 1;
layout.insets = new Insets(10,10,10,10);
Main_Panel.add(Confirm_Label, layout);
JTextField Confirm_Field = new JTextField(10);
layout.gridx = 1;
layout.gridy = 1;
layout.insets = new Insets(10,10,10,10);
Main_Panel.add(Confirm_Field, layout);
JButton Confirm = new JButton("Confirm");
Confirm.addActionListener(null);
layout.gridx = 0;
layout.gridy = 2;
layout.insets = new Insets(10,10,10,10);
Main_Panel.add(Confirm, layout);
New_Account.setContentPane(Main_Panel);
New_Account.pack();
New_Account.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
double balance;
balance = ((Number) Balance_Field.getValue()).doubleValue();
Confirm_Field.setText(Double.toString(balance));
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
create_GUI();
}
});
}
}
So far, I have tried using “this” and “null”, and I have also tried changing main so that it calls the create_GUI() method differently, but nothing works so far.
Kaleb Weikel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.