2017-06-29 65 views
0

我想從「PART3」的任何幫助控制JFrame嗎? StackOverflow的要求更多的信息;)所以我的想法是在PART3 GF,我知道這是不對的所以任何幫助控制JFrame其他無效?

import java.io.IOException; 
import javax.swing.JFrame; 

public class test { 
    public static void main(String[] args) throws IOException{ 
     SetUp g =new SetUp(); 
     g.PART2(); 
     g.PART3();  

}} 

class SetUp { 
    void PART2()throws IOException{ 
     JFrame f = new JFrame(); 

     f.setTitle("Test"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     // System.out.println(f); 
    } 

    void PART3()throws IOException{  
     SetUp g =new SetUp(); 
     g.f.setSize(128,128); 
     g.f.setLocation(10,10); 
     g.f.setVisible(true); 

     // System.out.println(g.f); 
    } 
} 

所以我的想法是在PART3 GF,我知道這是不對的所以任何幫助

+0

你是什麼意思控制JFrame? – Lemonov

回答

1

f需要現場才能以其他方式訪問它。

class SetUp { 

    private JFrame f; // `f` is now an instance field of the SetUp class 

    void PART2()throws IOException { 
     f = new JFrame(); 
     f.setTitle("Test"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    void PART3()throws IOException{ 
     // SetUp g =new SetUp(); 
     // you can directly access 'f' here, there's no need to create a new object 

     f.setSize(128,128); 
     f.setLocation(10,10); 
     f.setVisible(true); 
    } 
} 
+0

爲什麼要使用f字段並在SetUp類中創建SetUp對象的實例?這在這種情況下完全沒有必要。 – Lemonov

+1

@Lemonov hehe,我還沒有完成編輯,我只是​​重複使用他的代碼。 –

+0

非常感謝,這真是太棒了:) –