如何在靜態方法之間共享對象?這甚至可能嗎?有沒有更好的辦法?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?
}
}
請閱讀(並遵循)[Java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html) –