简体   繁体   English

从另一个类访问JFrame

[英]Access JFrame from another class

How can I access JFrame from another class? 如何从另一个类访问JFrame? I am trying to add a JLabel (jlabel_title) to my JFrame (frame). 我试图将JLabel(jlabel_title)添加到我的JFrame(框架)。

public class Frame_Main
{
    public static void createWindow()
    {
        JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(400,250));
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Frame_Menu frame_menu = new Frame_Menu();
        frame.setMenuBar(frame_menu.getMenubar());
        frame.setLayout(new BorderLayout());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        createTitle();
    }

    public static void createTitle()
    {
        //IF abfrage integrierieren ob jlabel leer ist
        JLabel jlabel_title = new JLabel("test");
        jlabel_title.setBackground(Color.BLUE);
        jlabel_title.setFont(new Font("Segoe UI", Font.BOLD, 20));
        jlabel_title.setVisible(true);

Error shows up here: 错误出现在这里:

        Frame_Main.createWindow(frame).add(jlabel_title, BorderLayout.NORTH);
    }
}

First, do not use static methods unless really required (there is no reason to do so here). 首先,除非确实需要,否则不要使用静态方法(这里没有理由这样做)。

Then, add the JFrame as a member to your class - it is then accessible from the class's methods: 然后,将JFrame作为成员添加到您的类中-然后可以从类的方法中对其进行访问:

public class Frame_Main {
    private JFrame frame = new JFrame();

    public void createWindow() {
    // ...
    }


    public void createTitle() {
    // ...
        frame.add(jlabel_title, BorderLayout.NORTH);
    }
}

In the calling code, you then need to create an instance of your Frame_Main class and call the createWindow() method: 然后,在调用代码中,您需要创建Frame_Main类的实例并调用createWindow()方法:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
           Frame_Main mainWindow = new Frame_Main();
           mainWindow.createWindow();
        }
    });
}

(you might change createWindow() into something like initializeWindow() since that is what the method actually does) (您可以将createWindow()更改为initializeWindow()之类的方法,因为这实际上是该方法的工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM