使用actionPerformed()和actionListener更改按钮文本

时间:2014-06-22 21:29:51

标签: java swing methods

我正在尝试根据点击的第一个按钮更改按钮的文本。如果我硬编码我希望传递的字符串值,但是当我尝试根据带有数组的方法的方法更改按钮文本时,actionPerformed()方法更改按钮的值没有问题字符串值,它不识别它。我觉得它很容易解决,但我似乎无法找到它。

以下是必要的课程:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class myJPanel6 extends JPanel implements ActionListener {

    myJButton b1, b2;

    public myJPanel6() {
        setLayout(new GridLayout(1, 1));
        //=====================================
        student st1 = new student("Michael", "Robinson", 20);
        //=====================================
        b1 = new myJButton(st1.getName());
        b1.addActionListener(this);
        add(b1);
        //=====================================
        b2 = new myJButton(st1.WhatIsUp());
        add(b2);
    }

    public void actionPerformed(ActionEvent event) {
        Object obj = event.getSource();
        if (obj == b1) {
            b2.setText(st1.whatIsUp());
        }
    }
}
class student {
    String firstName;
    String lastName;
    int age;
    String status;

    public student(String a, String b, int c) {
        firstName = a;
        lastName = b;
        age = c;

        if (age <= 25) {
            status = "Traditional";
        } else {
            status = "Non-Traditional";
        }
    }

    String getName() {
        return ("NAME = " + firstName + "  " + lastName + ", Age = " + age + ", Status = " + status);
    }

    int getAge() {
        return age;
    }

    String getStatus() {
        return status;
    }

    String WhatIsUp() {
        String b = "dunno";
        double r = Math.random();
        int myNumber = (int) (r * 3f);
        if (myNumber == 0) {
            b = "reading";
        }
        if (myNumber == 1) {
            b = "talking";
        }
        if (myNumber == 2) {
            b = "interacting";
        }
        return b;
    }
}

2 个答案:

答案 0 :(得分:1)

st1在构造函数的本地声明,这意味着无法从actionPerformed方法访问它。

您需要像{按钮

一样使st1成为实例变量

例如......

public class myJPanel6 extends JPanel implements ActionListener {

    myJButton b1, b2;
    private student st1;

public myJPanel6() {
    setLayout(new GridLayout(1, 1));
    //=====================================
    st1 = new student("Michael", "Robinson", 20);

<强>更新

如果没有进一步的信息,WhatIsUp方法是包私有的,这意味着它只能从声明类的包中访问,如果你想要你需要制作public

访问其他地方
public String WhatIsUp() {...

答案 1 :(得分:1)

您需要在WhatIsUp student中制作方法public,以便您可以调用它。退出Java中的访问修饰符默认为protected修饰符。

例如:

public String WhatIsUp() {
    String b = "dunno";

同样@MadProgrammer建议 - 您需要将st1设为instance variable


旁注:除了WhatIsUp之外,您的所有方法都以小写字母开头。您应该保持格式相同并将其更改为whatIsUp。这也遵循Java惯例。