在 Java 8 中,添加了我们将在本示例中使用的 Lambda 表达式。一切都与前面的示例相同,但在程序中,我们创建了一个方法 buttonPressed()
,并在该函数中,我们将文本字段中写入的消息打印到 JLabel
。
要将 ActionListener
添加到 JButton
,我们使用 addActionListener()
函数,在该方法中,我们使用 lambda 方法。我们使用作为 ActionEvent
对象的参数 e
,然后调用 buttonPressed()
方法。
import javax.swing.*;
public class JavaExample {
static JTextField jTextField;
static JLabel jLabel;
public static void main(String[] args) {
JFrame jFrame = new JFrame("Java Example");
jLabel = new JLabel();
jLabel.setBounds(50, 150, 350, 40);
jTextField = new JTextField();
jTextField.setBounds(50, 50, 150, 20);
JButton jButton = new JButton("Submit");
jButton.setBounds(50, 100, 100, 30);
jButton.addActionListener(e -> buttonPressed());
jFrame.add(jLabel);
jFrame.add(jButton);
jFrame.add(jTextField);
jFrame.setSize(400, 400);
jFrame.setLayout(null);
jFrame.setVisible(true);
static void buttonPressed() {
if (!jTextField.getText().equals("")) {
jLabel.setText(jTextField.getText());
} else {
jLabel.setText("Please write something in the edit box");
在这个程序中,我们使用继承的概念添加了 ActionListener
。
我们创建一个类 JavaExample
,然后扩展类 JFrame
并实现 ActionListener
接口。我们必须重写作为 ActionListener
接口一部分的 actionPerformed()
方法。
我们在 main()
方法之外声明 JFrame
组件变量,因为我们需要在函数外使用它。我们创建 JavaExample
类的构造函数并在其中设置所有组件。
要将 ActionListener
添加到 JButton
组件,我们调用 addActionListener()
方法并传递 this
,它指向当前类的上下文,因为当前类 JavaExample
实现 ActionListener
它是传递函数的有效上下文。
在 actionPerformed()
函数中,我们编写了按下按钮时要执行的操作。在 main()
方法中,我们创建 JFrame
的实例并设置其布局和可见性。
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JavaExample extends JFrame implements ActionListener {
static JTextField jTextField;
static JLabel jLabel;
static JButton jButton;
public static void main(String[] args) {
JFrame jFrame = new JavaExample();
jFrame.setLayout(null);
jFrame.setVisible(true);
public JavaExample() {
jLabel = new JLabel();
jLabel.setBounds(50, 150, 350, 40);
jTextField = new JTextField();
jTextField.setBounds(50, 50, 150, 20);
jButton = new JButton("Submit");
jButton.setBounds(50, 100, 100, 30);
jButton.addActionListener(this);
add(jLabel);
add(jButton);
add(jTextField);
setSize(400, 400);
@Override
public void actionPerformed(ActionEvent e) {
if (!jTextField.getText().equals("")) {
jLabel.setText(jTextField.getText());
} else {
jLabel.setText("Please write something in the edit box");
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn