[英]Access JFrame from another class
如何从另一个类访问JFrame? 我试图将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);
错误出现在这里:
Frame_Main.createWindow(frame).add(jlabel_title, BorderLayout.NORTH);
}
}
首先,除非确实需要,否则不要使用静态方法(这里没有理由这样做)。
然后,将JFrame
作为成员添加到您的类中-然后可以从类的方法中对其进行访问:
public class Frame_Main {
private JFrame frame = new JFrame();
public void createWindow() {
// ...
}
public void createTitle() {
// ...
frame.add(jlabel_title, BorderLayout.NORTH);
}
}
然后,在调用代码中,您需要创建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();
}
});
}
(您可以将createWindow()
更改为initializeWindow()
之类的方法,因为这实际上是该方法的工作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.