如何使用单独 class 中的方法更改 JButton 文本?

How to change JButton text with a method from a seperate class?

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

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

这是完整的class方法在

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 class 无法解析它

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

将您的按钮 public 声明为静态,并通过在前面添加其 class 名称来调用它。 所以如果你的 Button 在 class A 里面并且你想从 class B 访问它,你可以这样做:

A.buttonName.setText("abc");

记得声明为静态的。

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