【问题标题】:How to add an ActionListener during the main method如何在 main 方法中添加 ActionListener
【发布时间】:2018-06-20 15:10:51
【问题描述】:

我正在尝试制作一个计算 TextField 数字的程序。要让它开始计算,你必须按下一个按钮,为此我必须向按钮添加一个 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,但它必须在这里,至少我是这么认为的。我希望在缩短代码的同时没有删减其中的一些重要部分。

【问题讨论】:

    标签: java swing actionlistener actionevent


    【解决方案1】:

    选项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!");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2017-02-13
      • 2011-08-30
      相关资源
      最近更新 更多