NetBeans 和Swing - 动态添加JPanel到JDialog
我正在 NetBeans 中设计一个应用程序,如下面的屏幕截图所示。
当用户单击 JFrame 上的 JButton 时,会弹出一个 JDialog,要求用户输入使用数字键盘输入数值。我希望 JDialog 动态添加 2 个 JPanel。 JPanel 1 将包含一个用于输入的文本框。 JPanel 2 将包含一个数字键盘。我这样设计它们是为了我可以在需要时重复使用数字键盘。我面临的问题是在弹出的 JDialog 上动态显示这 2 个 JPanel。 JDialog 弹出为空。请看下面我的代码。谢谢大家,非常感谢您的帮助
这是 JDialog 的示例代码:
public class MyDialog extends javax.swing.JDialog {
public MyDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {//Add JPanel 2 (Numeric Keypad) to JDialog
Container contentPane = getContentPane();
NumericKeypadPanel nkp = new NumericKeypadPanel();
nkp.setLayout(new java.awt.BorderLayout());
contentPane.removeAll();
contentPane.add(nkp);
contentPane.validate();
contentPane.repaint();
}
});
}
这是 JPanel 2(数字键盘)的示例代码:
public class NumericKeypadPanel extends javax.swing.JPanel {
/** Creates new form NumericKeypadPanel */
public NumericKeypadPanel() {
initComponents();//Draws 10 number buttons
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上有两种方法
1) 通过在屏幕上保持
JDialog
大小(以像素为单位)添加新的JComponent
,所有 JCompoenets或者可以缩小其中的一部分
2) 通过调用
pack()
调整JDialog
的大小,然后JDialog
将调整我的 am 规则都可以通过使用 href="http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html" rel="nofollow noreferrer">标准 LayoutManager (AbsoluteLayout)
basicall there are two ways
1) add a new
JComponent
by holdingJDialog
size (in pixels) on the screen, all JCompoenetsor part of them could be shrinked
2) resize
JDialog
by callingpack()
, thenJDialog
will be resizedboth my a.m. rulles works by using Standard LayoutManagers (excepting AbsoluteLayout)
NumericKeypadPanel 的 initComponents() 函数中有什么内容?如果它实际上没有创建组件,您将不会在对话框中看到任何内容。我在 NumericKeypadPanel 的构造函数中添加了一行来更改该面板的背景颜色,事实上,它在对话框中显示为绿色面板。
What is in the initComponents() function of the NumericKeypadPanel? If it's not actually creating components, you're not going to see anything in the dialog. I added a single line to the NumericKeypadPanel's constructor to change the background color of this panel, and indeed, it shows up in the dialog as a green panel.