gpt4 book ai didi

java - 如何在main方法中添加ActionListener

转载 作者:行者123 更新时间:2023-12-02 02:05:10 25 4
gpt4 key购买 nike

我试图编写一个程序来计算文本字段的数字。要让它开始计算,您必须按下一个按钮,为此,我必须向按钮添加一个 ActionListener,但据我所知这是不可能的,因为您不能使用 this 在静态上下文中。

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;
}
}

我知道如何编写一个不在 main 方法中的 ActionListener,但它必须在 main 方法中,至少我是这么认为的。我希望在缩短代码时我没有删除其中的一些重要部分。

最佳答案

选项 1:实例化一个实现 ActionListener 的对象

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

选项 2:使用 lambda 函数(Java 8 或更高版本)

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

关于java - 如何在main方法中添加ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50951544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com