【问题标题】:How can an object access variables of the class it lives in对象如何访问它所在的类的变量
【发布时间】:2022-01-27 05:02:06
【问题描述】:

我有两节课。一个是我的 Javaswing Main 类,另一个是 Main 类中使用的组件:

main.java:

public class main{

    static int x = 10;
    Component comp = new Component();

    //Swing Stuff...

}

component.java:

public class Component{
    int y = ...

    //Swing stuff...
}

现在,我想知道是否或如何实现主类中的 y = x。这里的目标是在主类中有一些全局样式,我的所有 Swing 组件都可以读取这些样式。

【问题讨论】:

  • int y = main.x;?它是一个静态字段,因此您可以在没有 main 引用的情况下访问它。
  • 类名应以大写开头,以免与以小写开头的变量名混淆。
  • 在您的示例中,您必须将 x 传递给 Component。将全局样式放在它们自己的静态类中,并从任何需要它们的组件中引用样式。
  • 是的,将样式存储在单独的类中似乎是一个很好的解决方案。但是,由于它们是静态的,我无法更改它们。我将如何处理功能,例如暗模式,其中样式根据主类中的字段而变化?
  • 构造函数不能解决问题吗?公共组件(int valueForY){ this.y = valueForY;} 示例:ideone.com/e.js/w5Jzxi

标签: java swing aggregation


【解决方案1】:
public class Main {
  static int x = 10;

  public static void main(String[] args) {
    Component component = new Component();
    System.out.println(component.y);
    System.out.println(x);

    component.y = x;
    System.out.println(component.y);
    System.out.println(x);
  }
}

class Component {
  int y = 20;
}
20
10
10
10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2016-05-10
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    相关资源
    最近更新 更多