简体   繁体   English

Java,点击更改JLabel文本

[英]Java, change JLabel text on click

I'm new to this site and to Java programming and I'd greatly appreciate a bit of help. 我是这个网站和Java编程的新手,非常感谢您的帮助。 I'm trying to make a really simple program using SWING where the user clicks a button and a label's text changes from "Hello" to "Bonjour". 我正在尝试使用SWING制作一个非常简单的程序,其中用户单击一个按钮,并且标签的文本从“ Hello”更改为“ Bonjour”。 These are the two errors I'm getting: 这些是我得到的两个错误:

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");

Any ideas? 有任何想法吗? My code is here: 我的代码在这里:

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

You have to declare the JLabel in the class directly so you can access it from the handle function: 您必须直接在类中声明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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM