gpt4 book ai didi

java - StackOverflow 困惑

转载 作者:行者123 更新时间:2023-12-02 08:23:53 33 4
gpt4 key购买 nike

我是一个 java 新手,并且在 StackOverflow 错误/在类之间访问文件的能力方面遇到了一个非常令人困惑的问题。我知道根本原因可能是我进行了一些递归调用,但修复它的语法却让我无法理解。我认为这与类如何通过扩展另一个类进行链接有关 - 但是,如果 InputScreen 类不扩展 ViewController,我将无法访问我需要的方法。我已将高级代码放在下面(制作一个程序来跟踪汽油里程)。

这样做的目标是能够打开一个包含一些历史里程数据的 xml 文件(使用 doOpenAsXML() 方法),然后允许用户将数据添加到一些文本字段(在 InputScreen 类中定义),添加另一个数据指向ArrayList,然后使用doSaveAsXML方法保存。

有人对如何实现这项工作有想法吗?谢谢!!!


// Simple main just opens a ViewController window
public class MpgTracking {
public static void main(String[] args) {
ViewController cl = new ViewController();
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl.setVisible(true);
} // end main
}<p></p>

<p>public class ViewController extends JFrame {</p>

<pre><code> // the array list that I want to fill using the historical data
public ArrayList<MpgRecord> hist;

public ViewController() {
doOpenAsXML(); // open historical data, put into 'hist'
InputScreen home = new InputScreen ();
}

public void doSaveAsXML() {
// ...long block to save in correct xml format
}

public void doOpenAsXML() {
// ...long block to open in correct xml format
}
</code></pre>

<p>}</p>

<p>public class InputScreen extends ViewController {
// statements to define a screen with text fields and a 'Save' button
// statements to create a listener on the Save button
// statements to add to the ArrayList hist, opened in the ViewController method
doSaveAsXML();
}</p>

<p></p>

最佳答案

这似乎是您问题的根本原因:

but, if the InputScreen class doesn't extend the ViewController, I can't access the methods there that I need.

要访问另一个类中的(非静态)方法,您需要此类的对象。在您的情况下,InputStream需要拥有一个ViewController对象,而不是成为一个ViewController对象。 (同样,ViewController 不应该 JFrame,而是一个 - 尽管这不会产生问题。)

如果你改变这个,你就不会得到你的构造函数循环。

public class ViewController {

...

public ViewController() {
doOpenAsXML(); // open historical data, put into 'hist'
InputScreen home = new InputScreen (this); // give myself to our new InputScreen.
// do something with home
}

public void doSaveAsXML() {
// ...long block to save in correct xml format
}

public void doOpenAsXML() {
// ...long block to open in correct xml format
}


}

public class InputScreen {

private ViewController controller;

public InputScreen(ViewController contr) {
this.controller = contr;
}


void someMethod() {
// statements to define a screen with text fields and a 'Save' button
// statements to create a listener on the Save button
// statements to add to the ArrayList hist, opened in the ViewController method
controller.doSaveAsXML();
}
}

关于java - StackOverflow 困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4916020/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com