【问题标题】:How to change JButton text with a method from a seperate class?如何使用来自单独类的方法更改 JButton 文本?
【发布时间】:2019-09-30 02:31:13
【问题描述】:

我正在尝试在调用此方法时更改 JButton 上的文本

public Piece select() {
        if (this.unit_here != null) {
            namedisplay.setText(this.unit_here.name);
        }
    }

这是该方法所在的完整类

import java.util.ArrayList;

public class BoardWrapper {
    private Piece unit_here;
    private String terrain_here;
    private int terrain_duration;
    private int x;
    private int y;
    public BoardWrapper(int x2, int y2) {
        x = x2;
        y = y2;
    }
    public Piece select() {
        if (this.unit_here != null) {
            namedisplay.setText(this.unit_here.name);
        }
    }

}

我已将 JButton 声明为 public,但 BoardWrapper 类无法解决它

public JButton namedisplay = new JButton("Unit");

【问题讨论】:

  • BoardWrapper 类应该如何知道namedisplay 是某个其他类的属性。你需要告诉它。

标签: java swing text jbutton


【解决方案1】:

将您的按钮声明为 public static,并在之前添加其类名来调用它。 因此,如果您的 Button 在 A 类中并且您想从 B 类访问它,您可以这样做:

A.buttonName.setText("abc");

记得将它声明为静态的。

public static Button buttonName = new Button ("unit");

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2021-02-16
    • 2016-07-07
    • 1970-01-01
    • 2022-11-25
    相关资源
    最近更新 更多