【问题标题】:Accessing variable from Main window on PopUp window从弹出窗口的主窗口访问变量
【发布时间】:2014-03-18 09:09:15
【问题描述】:

我的主窗口 GUI 中有一个名为 totalCost 的私有字符串变量,名为 PriceCalculator 类,以及一个名为 getCost() 的 getter 方法。我需要在我的辅助窗口中访问这个变量,它作为一个事件从我的主窗口弹出。

这是我的第二个窗口:

public class ExtraWindow extends JDialog {
  public ExtraWindow(JFrame frame) {
    super(frame, "Calculations", true);
    this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    getContentPane().setLayout(null);
    this.setSize(300,300);
    centerWindow(this);
  }.......
   ....

如您所见,我认为第二个窗口将主窗口作为参数。 这是我需要第一个窗口中的总成本的地方:

 JLabel lblCost = new JLabel("Cost: ");

由于我需要使用它所使用的特定框架中的信息,因此我无法创建匿名或其他 PriceCalculator 并从那里获取它。我尝试执行 frame.getCost(),这导致我将 frame 转换为 PriceCalculator,但我的程序无法运行。

如何从第一个窗口访问这个变量,这是第二个窗口的参数?

抱歉,忘了补充,在第一个窗口中,事件发生的位置:

public class Event implements MouseListener {

    @Override
    public void mouseClicked(MouseEvent e) {
        new ExtraWindow(PriceCalculator.this);

    }

【问题讨论】:

  • public ExtraWindow(JFrame frame) 更改为public ExtraWindow(PriceCalculator frame),这样您现在可以直接访问PriceCalculator 及其所有方法...
  • 哇,谢谢,让我觉得自己很愚蠢。

标签: java swing user-interface jdialog


【解决方案1】:

你可以...

将 public ExtraWindow(JFrame frame) 更改为 public ExtraWindow(PriceCalculator frame),这样您现在可以直接访问 PriceCalculator 及其所有方法...

你可以...

提供一个附加参数,将值传递给构造函数...

public ExtraWindow(JFrame frame, double cost) {...

你可以...

ExtraWindow 中提供setCost 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多