微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从其他类向JFrame添加元素

如何解决从其他类向JFrame添加元素

在一次JFrame创建中,我有两个类:

public class Window extends JFrame {

    public void createWindow() throws IOException {
        setTitle(GeneralValues.PROGRAM_NAME);
        setSize(1100,600);
        setResizable(false);
        setDefaultCloSEOperation(JFrame.DO_nothing_ON_CLOSE);
        setLayout(null);
        setVisible(true); 
    }
}

第二秒钟我有一个JLabel

public class InitialConfiguration {

    Window w = new Window();

    public void main() {
        JLabel blauncherIcon = new JLabel();
        blauncherIcon.setBounds(100,100,100);
        blauncherIcon.setopaque(true);
        blauncherIcon.setText("Text");

        w.add(blauncherIcon);
    }
}

我的主要方法

public class Main {

    Window w = new Window();
    InitialConfiguration ic = new InitialConfiguration();

    public static void main(String[] args) {
    
         w.createWindow();
         ic.main();
    
    }

}

我想将InitialConfiguration类的标签添加Window类的框架,但是不幸的是,此代码创建了一个框架,但没有添加InitialConfiguration类的标签。可以做到吗?

解决方法

您不是在窗口类上启动Jframe的,我也不知道您的主类,因此我为您的理解而做了。检查此代码;

已编辑

主要:示例代码:

public class MainMenu{

   
    public static void main(String[] args) {
        Windows w = new Windows();
        InitialConfiguration ini = new InitialConfiguration(w);
        w.createWindow();
        ini.main();
    }
}

ICONFIG类示例代码:

public class InitialConfiguration {

    Window w;

    public InitialConfiguration(Windows w){
        this.w = w;
}
    public void main() {
        
        
        JLabel blauncherIcon = new JLabel();
        blauncherIcon.setBounds(100,100,100);
        blauncherIcon.setOpaque(true);
        blauncherIcon.setText("Text");

        w.add(blauncherIcon);
        w.repaint();
    }
}

Window类示例代码:

public class Window extends JFrame {

    public void createWindow(){
        setTitle("Your title");
        setSize(1100,600);
        setResizable(false);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setLayout(null);
        setVisible(true);
    }
}
,

您的问题是,您的Window实例出了错。您的InitialConfiguration的成员变量为Window,并向其添加了标签。但这与Window类中的Main实例不同。

总而言之,您创建并显示了该窗口,但从不显示实际上向其添加标签的第二个窗口。

总的来说,如果您真的想保持这种结构(我建议您这样做,但您可能有自己的理由),则将正确的Window实例作为方法参数应予以解决。

public class InitialConfiguration {

    // Removed second Window here
  
    public void main(Window w) { // rename this method please
        JLabel blauncherIcon = new JLabel();
        blauncherIcon.setBounds(100,100); // use layout managers
        blauncherIcon.setOpaque(true);
        blauncherIcon.setText("Text");
        w.add(blauncherIcon);
    }
}

和您的“主要”:

public class Main {

    Window w = new Window(); // rename the class Window please
    InitialConfiguration ic = new InitialConfiguration();

    public static void main(String[] args) {
    
         w.createWindow();
         ic.main(w);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。