[英]sending from jframe to java class and then accessing them from other jframe
[英]Accessing Components in JFrame from External Class
我无法访问JFrame中的多个组件以使用其setText(“...”)方法。 我的主要是一个单独的类,因为实际程序有许多窗口需要同时管理。
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");
}
我尝试了很多不同的方法,但是我并没有真正理解它们中的任何一个,而且它们都不允许我访问我需要的方法。
在GameWindow
类中创建一个setText(String text)
方法。 在该方法中,在需要更改的组件上调用setText
。
将JTextPane
的声明移出initialize
方法,使其成为一个参数,以便您可以在类中随时访问它。 要使其可以从另一个类访问,您可以将其公开或添加set方法。 像这样:
public class GameWindow {
private JTextPane gameTextPane;
...
private void initialize(){...}
...
public void setText(String s) {
gameTextPane.setText(s);
}
}
要从主类更改文本:
gW.setText("This is a cool text");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.