如何在 Java 运行时将面板动态添加到其他面板? [英] How do I dynamically add Panels to other panels at runtime in Java?
问题描述
我正在尝试再次进入 Java(已经有几年了).我从来没有真正用 Java 做过任何 GUI 编码.我一直在使用 Netbeans 来开始这个工作.
I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.
在工作中使用 C# 中的 winforms 时,我使用用户控件来构建我的 UI 部分并将它们动态添加到表单中.
When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically.
我一直在尝试像 C# 中的用户控件一样使用 JPanels
.我创建了一个名为 BlurbEditor
的 JPanel
表单.这有一些简单的控件.我试图在按钮事件的运行时将它添加到另一个面板.
I've been trying to use JPanels
like usercontrols in C#. I created a JPanel
form called BlurbEditor
. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event.
这是我认为可行的代码:
Here is the code that I thought would work:
mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();
不幸的是,这不起作用.我做错了什么?
This unfortunately is not working. What am I doing wrong?
推荐答案
我想通了.此处接受的答案下的评论对此进行了解释:动态添加的 JTable 不显示
I figured it out. The comments under the accepted answer here explain it: Dynamically added JTable not displaying
基本上我只是在 mainPanel.add() 之前添加了以下内容
Basically I just added the following before the mainPanel.add()
mainPanel.setLayout(new java.awt.BorderLayout());
这篇关于如何在 Java 运行时将面板动态添加到其他面板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!