本文介紹了StackOverflow混亂的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問題描述
我是一名Java新手,在StackOverflow錯(cuò)誤/在類之間訪問文件的能力方面有一個(gè)非常令人困惑的問題。我知道潛在的原因可能是我有一些遞歸調(diào)用,但修復(fù)它的語(yǔ)法讓我摸不著頭腦。我認(rèn)為這與類如何通過一個(gè)擴(kuò)展另一個(gè)擴(kuò)展鏈接有關(guān)–但是,如果InputScreen類不擴(kuò)展ViewController,我就不能訪問那里我需要的方法。我已經(jīng)把高級(jí)代碼放在下面(編寫一個(gè)跟蹤汽油里程的程序)。
這樣做的目標(biāo)是能夠打開包含一些歷史里程數(shù)據(jù)的XML文件(使用doOpenAsXML()方法),然后允許用戶將數(shù)據(jù)添加到一些文本字段(在InputScreen類中定義),將另一個(gè)數(shù)據(jù)點(diǎn)添加到ArrayList,然后使用doSaveAsXML方法保存。
有誰(shuí)有辦法讓這件事奏效嗎?謝謝!
// 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 }
public class ViewController extends JFrame {
// 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 }
}
公共類InputScreen擴(kuò)展了視圖控制器{
//定義帶有文本字段和‘保存’按鈕的屏幕的語(yǔ)句
//在保存按鈕上創(chuàng)建監(jiān)聽程序的語(yǔ)句
//要添加到ArrayList歷史記錄的語(yǔ)句,在ViewController方法中打開
DoSaveAsXML();
)推薦答案
這似乎是問題的根本原因:
但是,如果InputScreen類不擴(kuò)展ViewController,我就無(wú)法訪問那里我需要的方法。
要訪問另一個(gè)類中的(非靜態(tài))方法,您需要此類的對(duì)象。在您的情況下,InputStream將需要具有一個(gè)視圖控制器對(duì)象,而不是一個(gè)視圖控制器對(duì)象。(在同一行中,視圖控制器不應(yīng)該是JFrame,但應(yīng)該有JFrame--盡管這在這里不會(huì)產(chǎn)生問題。)
如果更改此設(shè)置,則不會(huì)獲得構(gòu)造函數(shù)循環(huán)。
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(); } }
這篇關(guān)于StackOverflow混亂的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,