我是这个网站和Java编程的新手,我非常感谢一些帮助。我正在尝试使用SWING创建一个非常简单的程序,用户单击一个按钮,标签的文本从“Hello”变为“Bonjour”。这是我得到的两个错误:
java:6: error: Lab4Part1 is not abstract and does not override abstract
method actionPerformed(ActionEvent) in ActionListener
public class Lab4Part1 extends JFrame implements ActionListener {
java:25: error: cannot find symbol
label.setText("Bonjour");
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Lab4Part1 extends JFrame implements ActionListener {
public Lab4Part1() {
super("Lab 4 Part 1");
Container contentPane = getContentPane();
JPanel panel = new JPanel();
contentPane.add(panel);
setSize(400, 100);
setVisible(true);
JLabel label = new JLabel("Hello");
panel.add(label);
JButton button = new JButton("Translate to French");
panel.add(button);
button.addActionListener(this);
}
public void handle(ActionEvent event) {
label.setText("Bonjour");
}
public static void main(String[] args) {
Lab4Part1 myFrame = new Lab4Part1();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:4)
您必须直接在类中声明JLabel,以便可以从handle函数访问它:
public class Lab4Part1 extends JFrame implements ActionListener {
JLabel label;
public Lab4Part1() {
super("Lab 4 Part 1");
Container contentPane = getContentPane();
JPanel panel = new JPanel();
contentPane.add(panel);
setSize(400, 100);
setVisible(true);
label = new JLabel("Hello");
panel.add(label);
JButton button = new JButton("Translate to French");
panel.add(button);
button.addActionListener(this);
}
public void handle(ActionEvent event) {
label.setText("Bonjour");
}