2017-06-29 117 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

非常感谢,这真是太棒了:) –