【问题标题】:Java: how to access class variables when using add(ClassName) in a JFrameJava:在 JFrame 中使用 add(ClassName) 时如何访问类变量
【发布时间】:2018-09-04 09:20:52
【问题描述】:

我需要访问 Surface 类中的两个变量(screenWidthscreenHeight)。这就是我目前实现的方式:

public class WheelOfFortune extends JFrame {

public WheelOfFortune() {

    initUI();
}

private void initUI() {

    Surface newSurface = new Surface();

    add(newSurface);

    setSize(newSurface.screenWidth, newSurface.screenHeight);

    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {

    EventQueue.invokeLater(() -> {
        WheelOfFortune ex = new WheelOfFortune();
        ex.setVisible(true);
        ex.setResizable(false);
    });
}

}

是否可以通过使用此代码来做同样的事情?怎么样?

public class WheelOfFortune extends JFrame {

public WheelOfFortune() {

    initUI();
}

private void initUI() {

    add(new Surface());

    setTitle("The Wheel of Fortune");

    setSize(???.screenWidth, ???.screenHeight);

    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {

    EventQueue.invokeLater(() -> {
        WheelOfFortune ex = new WheelOfFortune();
        ex.setVisible(true);
        ex.setResizable(false);
    });
}
}

【问题讨论】:

  • 一个问题:为什么?
  • 更少的代码行数、好奇心和正确做事的意愿。

标签: java class variables


【解决方案1】:

是和不是。

是的:

setSize(((Surface)getComponent(getComponentCount()-1)).screenWidth, ((Surface)getComponent(getComponentCount()-1)).screenHeight);

没有:

看到是的。

您最初的解决方案是干净、简短且正确的。

【讨论】:

  • 谢谢你的例子。干杯。
猜你喜欢
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多