【问题标题】:NetBeans & Swing - dynamically add JPanel to JDialogNetBeans & Swing - 将 JPanel 动态添加到 JDialog
【发布时间】:2012-02-16 15:55:36
【问题描述】:

我正在 NetBeans 中设计一个应用程序,如下面的屏幕截图所示。

当用户单击 JFrame 上的 JButton 时,会弹出一个 JDialog,要求用户使用数字键盘输入数值。我希望 JDialog 动态添加 2 个 JPanel。 JPanel 1 将包含一个用于输入的文本框。 JPanel 2 将包含一个数字键盘。我以这种方式设计它们,以便我可以在需要时重复使用数字小键盘。我面临的问题是在弹出的 JDialog 上动态显示这两个 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
    }
}

【问题讨论】:

    标签: java swing netbeans jpanel jdialog


    【解决方案1】:

    基本上有两种方式

    1) 通过在屏幕上按住 JDialog 大小(以像素为单位)添加新的 JComponent,所有 JCompoenets 或者其中一部分可以缩小

    2) 通过调用pack() 调整JDialog 的大小,然后JDialog 将被调整大小

    both my a.m. rulles works 使用 Standard LayoutManagersAbsoluteLayout 除外)

    【讨论】:

      【解决方案2】:

      NumericKeypadPanel 的 initComponents() 函数是什么?如果它实际上没有创建组件,您将不会在对话框中看到任何内容。我在 NumericKeypadPanel 的构造函数中添加了一行来更改此面板的背景颜色,实际上,它在对话框中显示为绿色面板。

      public NumericKeypadPanel() {
          //initComponents();//Draws 10 number buttons
          setBackground(Color.green);
      }
      

      【讨论】:

      • initComponents() 函数是绘制数字按钮。我不小心找到了解决方案。在 NetBeans 中,您可以简单地将定制的 JPanel 拖放到 JDialog 或 JFrame。解决方案非常简单,我之前从未想过。我需要更多地使用 NetBeans 来发现所有隐藏的功能。
      猜你喜欢
      • 2016-10-25
      • 1970-01-01
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多