Why won't my Jbutton do anything on click?

1.4k views Asked by At

I've been trying to make it so my button will close out of the frame on click but it never does anything. I've looked through several stackoverflow threads but none of them seems to work on my this.. here is what I have so far

    JButton start = new JButton("Start");
    start.setBounds(251, 216, 119, 23);

    start.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent evt) {

            try {
                int hpToEat = Integer.parseInt(GUI.textField.getText());
                Frost.hp = hpToEat;
            } catch(NumberFormatException nfe) {
                GUI.textField.setText("");
            }
            setVisible(false);
        }
    });
    contentPane.add(start);

I have tried making a closeFrame method which uses super.dispose(); and I've also tried system.exit(0);

Does anyone have any idea as to why My button won't do What i want it to do?

Someone requested the rest of my code so here it is:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;
import javax.swing.JTextField;
import javax.swing.JButton;


public class GUI extends JFrame{

private JPanel contentPane;
public static JTextField textField;


/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GUI frame = new GUI();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public GUI() {

    //LABELS ===================================================================================================
1

There are 1 answers

1
kiheru On BEST ANSWER

The problem is that GUI.textfield is not what you think it is. You're shadowing the field here:

JTextField textField = new JTextField();

That creates a local variable by the name textField, it does not set the static field you're using in the action listener. A quick fix would be writing just:

textField = new JTextField();

However, I recommend getting out of the habit of using static fields. That approach does not scale. Furthermore, don't use absolute positioning. It leads to no end of trouble (just browse a few questions in the swing tag for examples). Learn to use layout managers right from the start.