user9871751
user9871751

Reputation:

How to add an ActionListener during the main method

I was trying to make a program that calculates the numbers of the TextField. To let it start calculating you have to press a button and to do that I have to add an ActionListener to the button but it isn't possible as far as I can see, because you can't use this in a static context.

import javax.swing.*;

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

public abstract class math extends JFrame implements ActionListener { 

 public static void main(String[] args) {   

    JFrame frame = new JFrame();

    JButton button = new JButton("text");

    JPanel mainPanel =new JPanel();

    JLabel mainLabel = new JLabel("text");

    JTextField mainField = new JTextField(5);

    button.addActionListener(this);

    mainPanel.add(mainLabel);
    mainPanel.add(mainField);

    mainPanel.add(button);

    frame.setTitle("text");
    frame.setSize(1000, 700);
    frame.setVisible(true);

    frame.add(mainPanel);

    //when the button something gets done here

    double num = Double.valueOf(mainField.getText());
    num * 4;
}
}

I know how to write an ActionListener that is not in the main method but here it has to be, at least I think so. I hope while shortening the code I didn't cut out some important parts of it.

Upvotes: 0

Views: 1604

Answers (1)

khelwood
khelwood

Reputation: 59240

Option 1: instantiate an object that implements ActionListener

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // whatever you need to do
        System.out.println("The button was pressed!");
    }
});

Option 2: use a lambda function (Java 8 or above)

button.addActionListener(e -> {
    // whatever you need to do
    System.out.println("The button was pressed!");
});

Upvotes: 2

Related Questions