如何在静态方法之间共享一个对象?这有可能吗?有没有更好的办法?
在我的代码中,我在一个类中有一个框架。我有不同的静态方法来处理同一个类中的这个框架。我在另一个类中调用这些方法。
对于 swing 有更好的方法吗?本质上我想创建一个框架,我可以在其中通过其他类的方法编辑大小、颜色和内容(这些类将具有我将在此框架上使用的面板)。
调用静态方法的类:
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?
}
}
最佳答案
您的代码违反了各种面向对象的原则,首先是信息隐藏/封装
您的变量 appFrame
应该声明为private 并且只能通过 loginFrames
类访问。
此外:由于变量 appFrame
未声明为 static 因此无法从该类中的静态方法(直接)访问它。
解决方案是从方法中删除 static 关键字并通过类的对象访问它们(在 中使用 objects 听起来很奇怪吗>面向对象语言?)
关于Java - 如何在同一个类的不同静态方法中共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44351822/