2013-05-15 37 views
0

我無法訪問JFrame中的幾個組件以使用它們的setText(「...」)方法。我的主要是在一個單獨的班級,因爲實際的程序有很多窗口需要同時管理。從外部類訪問JFrame中的組件

public GameWindow() { 

    initialize(); 
    gameFrame.setVisible(true); 
} 

private void initialize() {  
    gameFrame = new JFrame(); 

JTextPane gameTextPane = new JTextPane();  // text pane to contain all game text 
    gameTextPanel.add(gameTextPane); 

這是我的主:

public class GameMain { 
    public static GameWindow gW = new GameWindow(); 
    //I have tried using the code below with various numbers, but the "setText()" method is never available 
    gW.getGameFrame().getContentPane().getComponent(x); 
} 

我試圖從獨立的類設置的這個文本,但我不能訪問該組件。 最後,最終的代碼應該是這個樣子:

public static void main(String[] args) { 

    // make the GUI and initilize 
    changeTheText(); 
} 

public static void changeTheText() { 
    [CODE TO ACCESS TEXTFIELD].setText("Hello World"); 
} 

我都試過,我發現周圍尋找許多不同的方法,但我實在不明白其中的任何,和他們都不仍然讓我訪問我需要的方法。

+0

默認有getsetters或約構造有一些變化,爲更好地幫助越早發佈的[SSCCE(HTTP:/ /sscce.org/),簡短,可運行,可編譯,僅僅是關於JFrame – mKorbel

+0

*「實際的程序有很多窗口」*參見[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/ a/9554657/418556) –

回答

1

JTextPane的聲明移出initialize方法,使其成爲參數,以便您可以隨時從課程內部訪問它。要使其可以從另一個類訪問,您可以將其公開或添加一個設置方法。就像這樣:

public class GameWindow { 
    private JTextPane gameTextPane; 
    ... 
    private void initialize(){...} 
    ... 
    public void setText(String s) { 
     gameTextPane.setText(s); 
    } 
} 

若要更改主類文本:

gW.setText("This is a cool text"); 
+0

謝謝,正是我在找的! – Aaron

1

在您的GameWindow類中創建一個setText(String text)方法。在該方法中,需要更改的組件上調用setText

+0

我會怎樣稱呼它? gameTextPane.setText(文本);返回一個無法找到的錯誤,而類似的變化會給出類似的錯誤。 – Aaron

+0

你可以發佈堆棧跟蹤嗎?這很難說「主要」 java.lang.Error的是怎麼回事,沒有它 – dratewka

+0

異常螺紋:未解決的問題,編譯:gameTextPane不能在GameMain.main在GameWindow.setGameText(GameWindow.java:376) \t解決 \t (GameMain.java:44)' – Aaron