2017-07-27 37 views
0

我有这样的问题:的Java:不能更改另一个Java文件中的JFrame组件的内容

  • 我有一个JFrame GUI类GUIView.java:

     public class GUIView extends JFrame{ 
    
         //other instance variables 
         .... 
         public JTextArea gameGuide; 
    
         //constructor 
         public GUIView(){ 
          ... 
          initGUI(); 
    
         } 
         //init GUI 
         public void initGUI(){ 
          //add other components 
          ... 
          gameGuide = new JTextArea(); 
    
          //set layout 
          ... 
          add(gameGuide); 
         } 
         public void setText(String s){ 
          this.gameGuide.setText(s); 
         } 
    
         public void showGame(){ 
          GUIView f = new GUIView() ; 
          f.setSize(450,600); 
          f.setTitle("TIC TAC TOE ONLINE"); 
          f.setResizable(false); 
          f.setLocationRelativeTo(null); 
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
          f.setVisible(true); 
         } 
        } 
    

    - 然后我有一个文件所谓Worker.java

    public class Worker { 
        public GUIView guiView; 
    
        public Worker(GUIView guiView) { 
         this.guiView= guiView; 
        } 
    
        public static void main(String[] args){ 
         GUIView guiView = new GUIView(); 
         Worker worker = new Worker(guiView); 
         guiView.setText("testing if this will work"); 
         guiView.showGame(); 
        } } 
    

的GUI工作,它显示了一个空白的游戏指南文本区域。

在Worker.java中,我试着改变gameGuide的内容,但是gameGUI.setText()中的字符串没有显示出来。

我试过设置可见true - > false - > true,仍然没有工作。

请解释为什么?有没有办法我可以改变组件的内容gameGuide textArea在Worker.java中?

回答

2

这可能有帮助。实际上,创建了两个不同的GUIView JFrame。

public void showGame(){ 
      setSize(450,600); 
      setTitle("TIC TAC TOE ONLINE"); 
      setResizable(false); 
      setLocationRelativeTo(null); 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      setVisible(true); 
} 
+0

谢谢!你,Raju和Andre先生已经彻底解决了我的问题! –

1

您每次都在showGame()方法中创建一个新的GUIView。无论你之前在另一个上设置了什么,你总会看到那个。

public static void main(String[] args){ 
    GUIView guiView = new GUIView(); // creates a GUIView 
    Worker worker = new Worker(guiView); 
    guiView.setText("testing if this will work"); // changes the created GUIView 
    guiView.showGame(); // creates an entirely new GUIView and shows that one instead 
} 
+0

谢谢!我现在看到问题了!你,安德烈先生和拉朱已经帮助过我了! –

相关问题