Reputation: 1016
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.
Upvotes: 0
Views: 2732
Reputation: 1533
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");
Upvotes: 1
Reputation: 2114
Create a setText(String text)
method in your GameWindow
class. In that method call setText
on the components you need to change.
Upvotes: 1