0

I am having trouble accessing several components in a JFrame to use their setText("...") method. My main is in a seperate class, because the actual program has many windows that need to be managed at the same time.

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);

And this is my main:

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);
}

I am trying to set the text of this from a seperate class, but I can not access the components. Ultimately, the final code should look something like this:

public static void main(String[] args) {

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

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

I have tried many different methods I've found searching around, but I don't really understand any of them, and none of them still allow me to access the methods I need.

Aaron
  • 992
  • 3
  • 15
  • 33
  • by default there are getsetters or a few variations about constructor, for better help sooner post an [SSCCE](http://sscce.org/), short, runnable, compilable, just about JFrame – mKorbel May 15 '13 at 12:53
  • *"the actual program has many windows"* See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson May 15 '13 at 13:04

2 Answers2

1

Create a setText(String text) method in your GameWindow class. In that method call setText on the components you need to change.

dratewka
  • 2,104
  • 14
  • 15
  • How would I call that? gameTextPane.setText(text); returns an error that it can't be found, and similar variations give similar errors. – Aaron May 15 '13 at 12:59
  • Could you post the stacktrace? It's difficult to tell what's going on without it – dratewka May 15 '13 at 13:15
  • Exception in thread "main" java.lang.Error: Unresolved compilation problem: gameTextPane cannot be resolved at GameWindow.setGameText(GameWindow.java:376) at GameMain.main(GameMain.java:44)' – Aaron May 15 '13 at 13:57
1

Move the declaration of the JTextPane out of the initialize method to make it a parameter so you can acces it anytime from within the class. To make it accessible from another class you can either make it public or add a set method. Like this:

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

To change your text from the main class:

gW.setText("This is a cool text");
DeadlyJesus
  • 1,503
  • 2
  • 12
  • 26