如何在Java中使用在另一个方法上创建的对象?

如何在Java中使用在另一个方法上创建的对象?,java,swing,methods,jframe,jlabel,Java,Swing,Methods,Jframe,Jlabel,我是Swing新手,我想知道如何使用在一个方法上实例化的对象,在另一个方法中。我需要将标签添加到frame对象中,但我不想从createFrame方法执行此操作。那么,我能做什么 public class Main { public static void main(String[] args) { FrameCreation.createFrame(600, 600, "Test"); FrameCreation.createLabel("W

我是Swing新手,我想知道如何使用在一个方法上实例化的对象,在另一个方法中。我需要将
标签
添加到
frame
对象中,但我不想从
createFrame
方法执行此操作。那么,我能做什么

public class Main 
{
    public static void main(String[] args) 
    {
        FrameCreation.createFrame(600, 600, "Test");
        FrameCreation.createLabel("Whatever");
    }
}

public class FrameCreation 
{
    public static JFrame createFrame(int width, int height, String name) 
    {
        JFrame frame = new JFrame(name);
        frame.setVisible(true);
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        return frame;
    }

    public static JLabel createLabel(String text) 
    {
        JLabel label = new JLabel(text);
        return label;
    }
}

首先,如果要将JLabel添加到JFrame,必须创建一个JPanel。顺序如下:

JFrame->JPanel->JLabel

所以你可以写(主要):


我已经找到了解决方案,现在我们开始:

public class Main 
{
    public static void main(String[] args) 
    {
        FrameCreation.createFrame(600, 600, "Test").add(FrameCreation.createLabel("Whatever"));
    }
}

你正在返回新创建的帧。。。但是在
main
方法中完全忽略它。提示:
JFrame-frame=FrameCreation.createFrame(600600,“测试”)并从那里开始…不要使用所有静态方法。我建议您从阅读Swing教程了解Swing基础知识开始。可以从上一节中的
LabelDemo
开始,以获得更好的代码结构。我是否理解您不再需要帮助?请考虑添加你自己的答案(如果没有人提供更好的答案,你将在48小时内接受)。这样,人们就不用花时间去寻找你不需要的解决方案了。请看@Thiagofronato,不要破坏你自己的问题。它们需要作为问题留给未来的读者。如果您不想这样做,请将其全部删除,但这不是此社区的目的。没有理由首先将标签添加到面板中。框架的内容窗格是JPanel。您只需将标签添加到框架中,它就会被添加到内容窗格中。您需要将JLabel添加到可见的容器中,否则它将无法显示在屏幕上。@SimoneC。在容器验证之前,
setVisible()
之后添加到容器中的组件不会显示。@SimoneC.,您可以将组件添加到框架中(不需要额外的面板),然后使用
frame.pack()
然后使用
frame.setVisible()
显示框架及其所有组件。
public class Main 
{
    public static void main(String[] args) 
    {
        FrameCreation.createFrame(600, 600, "Test").add(FrameCreation.createLabel("Whatever"));
    }
}