【问题标题】:How do I change the JLabel text by clicking on my JButton?如何通过单击我的 JButton 来更改 JLabel 文本?
【发布时间】:2013-10-22 00:11:03
【问题描述】:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class myAction extends JFrame implements ActionListener {
    myAction() {

        super("Lab 4 Question 1");

        Container c = getContentPane();
        JPanel p = new JPanel();
        JPanel p1 = new JPanel();

        JButton b = new JButton("Button 1");
        JButton b1 = new JButton("Button 2");
        JButton b2 = new JButton("Button 3");

        Font newFont = new Font("SERIF", Font.BOLD, 16);
        b1.setFont(newFont);
        b1.addActionListener(this);

        JLabel l = new JLabel("Hello.");

        p.add(b);
        p.add(b1);
        p.add(b2);
        p1.add(l);
        c.add(p);
        c.add(p1);

        c.setLayout(new FlowLayout());
        setSize(300, 300);
        show();
    }

    public static void actionPerformed (ActionEvent e) {
        if(e.getSource().equals(b))
        {
            this.l.setText("Testing");
        }
    }


    public static void main(String[] args) {
        myAction output = new myAction();
    }
}

如何让我的 JButton b1 改变我的 JLabel l 的值?我对编程很陌生,所以对于你们注意到的任何错误,我深表歉意!每当我单击按钮时,我只需要更改它,我认为我做对了,但找不到我的符号,我很确定我不应该将它们传递给方法:S

【问题讨论】:

    标签: java awt jbutton jlabel


    【解决方案1】:

    好吧,您甚至没有为您的按钮添加ActionListener 并将actionPerformed 方法设置为非静态(只需删除static)。这解决了一个问题:

    b.addActionListener(this);
    

    另外,我建议使用匿名内部类,而不是直接在您的类中实现ActionListener。像这样:

    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            //Do stuff
        }
    });
    

    另外,让你的JButton's 变种。作为实例变量(将它们移到构造函数之外)。

    【讨论】:

    • @DáithíCushen 很简单:当您实现 ActionListener 时,actionPerformed 不能是静态的。其次,通过在其中一个按钮的addActionListener 方法中传递this 关键字来添加ActionListener。第三,将那些JButton 声明(即JButton b = new JButton("Button 1");)移到构造函数之外(就在下面:class myAction extends JFrame implements ActionListener {)。
    【解决方案2】:

    b 对您的 actionPerformed 方法不可见,因为它是在构造函数中定义的。您需要将变量 b 移到 myAction() 之外。

    class myAction extends JFrame implements ActionListener {
        JButton b;
        myAction() {
            b = new JButton("Click");
    

    【讨论】:

    • 仍然出现3个错误,仍然找不到我的符号l,myAction.java:39:错误:myAction中的actionPerformed(ActionEvent)无法在ActionListener中实现actionPerformed(ActionEvent) public static void actionPerformed(ActionEvent e ) { and myAction.java:40: error: non-static variable b cannot be referenced from a static context if(e.getSource().equals(b))
    猜你喜欢
    • 2018-06-05
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多