有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检索变量并将其传递给其他类

我创建了一个平均值程序,其中average变量包含平均值。我希望在图形用户界面中打印出值,但我的GUI在另一个类中

我似乎无法让变量“平均”在我的不同班级发挥作用。无论我怎么尝试,我的平均成绩是“找不到符号”。这是我的密码:

System.out.println("this is the average: "+ average);
// this perfectly prints out the average from the
// class "public void test" and the method "calcAverage"

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
    // this is my button in a different class where I want
    // my average to append to (print to the GUI) - and my
    // obviously non-working attempt at it
    JTextArea.append (test.calcAverage(average));
}

共 (1) 个答案

  1. # 1 楼答案

    I want the average to be printed out in my graphical user interface, but my gui is in a different class.

    让gui类提供一个回调方法,以允许可视化地更新信息

    摇摆中:

    public MyFrame extends JFrame implements MyFrameCallback{
    
       public void updateAverage(double average){
           ... // update the graphical widget 
       }
    }
    

    其中MyFrameCallback是一个接口,例如:

    public interface MyFrameCallback{
       void updateAverage(double average);
    }
    

    现在,当您创建我们将调用MyAverageModel的模型类时,在其构造函数中添加MyFrameCallback

    public MyAverageModel (MyFrameCallback myFrameCallback){
       this.myFrameCallback = myFrameCallback;
    }
    

    现在,在MyAverageModel中计算平均值时,可以调用gui的回调:

    public calculAndUpdateAverage(){
       ...
       double average = ...;
       myFrameCallback.updateAverage(average);
    }