Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法从其他类访问数据_Java_Actionlistener - Fatal编程技术网

Java 无法从其他类访问数据

Java 无法从其他类访问数据,java,actionlistener,Java,Actionlistener,我叫加布 我正在制作一个程序,通过点击一个按钮,使一页消失另一页。问题是,我无法从我的两个类中传递适当的数据。听起来可能很奇怪,但我的代码如下: 我的第一节课(1班): 事实上,我希望程序将'msg1'可见性设置为false和'msg2'可见性设置为true,但我无法使程序工作,因为第二个类不知道什么是'msg1'和'msg2'。请帮帮我 关于,-Gab对于能够使用对象的方法,它需要对该对象的引用。您正在创建一个Motour实例,但是您没有将任何对象传递到此Motour实例,因此它除了自身之外没

我叫加布

我正在制作一个程序,通过点击一个按钮,使一页消失另一页。问题是,我无法从我的两个类中传递适当的数据。听起来可能很奇怪,但我的代码如下:

我的第一节课(1班):

事实上,我希望程序将'msg1'可见性设置为false和'msg2'可见性设置为true,但我无法使程序工作,因为第二个类不知道什么是'msg1'和'msg2'。请帮帮我


关于,-Gab

对于能够使用对象的方法,它需要对该对象的引用。您正在创建一个Motour实例,但是您没有将任何对象传递到此Motour实例,因此它除了自身之外没有对任何对象的引用

为了使Moteur类能够调用msg1和msg2的方法,您需要将对这两个对象的引用传递给Moteur:

public class Moteur implements ActionListener {
    private JLabel messageToHide;
    private JLabel messageToShow;

    public Moteur(JLabel messageToHide, JLabel messageToShow) {
        this.messageToHide = messageToHide;
        this.messageToShow = messageToShow;
    }

    public void actionPerformed(ActionEvent e) {
        messageToHide.setVisible(false);
        messageToShow.setVisible(true);
    } 
}
然后,当您创建汽车旅馆时,您会给他们两个标签来隐藏和显示:

Moteur moteur = new Moteur(msg1, msg2);

对msg使用getter和setter。

奇怪为什么要使用两个标签。只需使用一个并使用
setText()
public class Moteur implements ActionListener {
    private JLabel messageToHide;
    private JLabel messageToShow;

    public Moteur(JLabel messageToHide, JLabel messageToShow) {
        this.messageToHide = messageToHide;
        this.messageToShow = messageToShow;
    }

    public void actionPerformed(ActionEvent e) {
        messageToHide.setVisible(false);
        messageToShow.setVisible(true);
    } 
}
Moteur moteur = new Moteur(msg1, msg2);