我第一次通過YouTube 上的教程學習如何使用 Java Swing 。我已經到達了涵蓋按鈕的部分,并且一直在遵循 T 的代碼。但是,在嘗試測驗按鈕以便在我使用該actionPerformed方法時它會列印出單詞“test”時,我的按鈕不會列印出單詞。
您可以在此處找到該測驗的原始代碼:
主.java
package com.learnjava;
public class Main {
public static void main(String[] args) {
new MyFrame();
}
}
MyFrame.java
package com.learnjava;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame implements ActionListener{
JButton button;
MyFrame() {
JButton button = new JButton();
button.setBounds(200, 100, 100, 50);
button.addActionListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
this.add(button);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
System.out.println("test");
}
}
}
每當我使用前面的代碼按下按鈕時,它都不會列印出“test”這個詞。如果我使用 lambda 運算式,它會起作用。
MyFrame.java(使用 lambda 運算式更新)
package com.learnjava;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame implements ActionListener{
JButton button;
MyFrame() {
JButton button = new JButton();
button.setBounds(200, 100, 100, 50);
button.addActionListener(e -> {System.out.println("test");}); // updated with lambda expression
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
this.add(button);
}
}
I've been trying to find a reason online as to why the former code does not work. I've seen one question but it was left unanswered. While I could settle for using the lambda expression instead, I would still like to understand how to write the former code correctly if I was doing something wrong. Thank you in advanced!
Note: If it is relevant for some reason, the IDE I am using is IntelliJ and my JDK is version 12.
uj5u.com熱心網友回復:
改變:
JButton button = new JButton();
到:
button = new JButton();
第一個是隱藏類屬性的區域變數。
第二個類也有同樣的問題,但是由于它(按鈕創建、添加監聽器、添加到 GUI)都在一個代碼部分中完成,所以從不使用 class 屬性并不明顯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405476.html
標籤:
