2017-06-04 95 views
2

如何在靜態方法之間共享對象?這甚至可能嗎?有沒有更好的辦法?Java - 如何在同一類中的不同靜態方法內共享對象

在我的代碼中,我在一個類中有一個框架。我有不同的靜態方法來處理同一個類中的這個框架。我將這些方法稱爲另一個類。

有沒有更好的方式做這個擺動?基本上我想創建一個框架,在其中我可以通過其他類的方法(這些類將有我將在此框架上使用的面板)編輯大小,顏色和內容。

類調​​用靜態方法:

import javax.swing.*; 

public class Main{ 

    // Display Login Window 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> { 
      try 
      { 
       new loginFrames(); 
       loginFrames.showFrame("hello", 1200, 800); 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 

     }); 
    } 
} 

類與靜態方法:

import javax.swing.*; 
import java.awt.*; 

public class loginFrames{ 

    public JFrame appFrame; 


    public void createFrame(String frameName, int frameW, int frameH) { 

     // Create JFrame with frame name, width, and height 
     appFrame = new JFrame(frameName); 
     appFrame.setSize(frameW, frameH); 

     // Get the content pane and set the background colour black 
     Container absFrameContentPane = appFrame.getContentPane(); 
     absFrameContentPane.setBackground(Color.BLACK); 

     // Show the frame 
     appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     appFrame.setVisible(true); 
    } 

    // Callable from Main class 
    public static void showFrame(String frameName, int frameW, int frameH) { 
     loginFrames applicationFrame = new loginFrames(); 
     applicationFrame.createFrame(frameName, frameW, frameH); 
    } 

    // Callable from Main class 
    public static void appAddPanel(String frameName, int frameW, int frameH) { 
    // How do I call the same object above, here? 
    } 
} 
+0

請閱讀(並遵循)[Java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html) –

回答

1

你的代碼違反各種OO原則,首先信息隱藏/封裝

您的變量appFrame應聲明爲私人並且只能從loginFrames類訪問。

另外:由於變量appFrame未聲明靜態所以它不能從該類的靜態方法(直接)訪問。

的解決方案是從方法中除去靜態鍵字,並且通過這個類的一個對象訪問它們(這是否聲音weired使用對象面向語言的對象?)

0

對我而言,我更喜歡爲您的JFrame選項使用外部文件。 FileReader用於從文件中獲取值,循環並將它們分配給數組或變量。和PrintWriter更改選項。希望得到這個幫助

相關問題