jadrijan
jadrijan

Reputation: 1446

NetBeans & Swing - dynamically add JPanel to JDialog

I am designing an application in NetBeans, as illustrated in the screenshot below.

enter image description here

When the user clicks on a JButton on a JFrame, a JDialog pops-up asking the user to enter a numeric value using a numeric keypad. I would like the JDialog to dynamically add 2 JPanels. JPanel 1 will contain a textbox for input. JPanel 2 will contain a numeric keypad. I designed them this way so that I could reuse the numeric keypad whenever I need it. The problem I am facing is displaying dynamically these 2 JPanels on the JDialog that pops-up. JDialog pops-up empty. Please take a look at my code below. Thank you all, I appreciate your help

This is the sample code of 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();
            }
        });
    }

This is the sample code for JPanel 2 (Numeric Keypad):

public class NumericKeypadPanel extends javax.swing.JPanel {

    /** Creates new form NumericKeypadPanel */
    public NumericKeypadPanel() {
        initComponents();//Draws 10 number buttons
    }
}

Upvotes: 1

Views: 4090

Answers (2)

mKorbel
mKorbel

Reputation: 109813

basicall there are two ways

1) add a new JComponent by holding JDialog size (in pixels) on the screen, all JCompoenets or part of them could be shrinked

2) resize JDialog by calling pack(), then JDialog will be resized

both my a.m. rulles works by using Standard LayoutManagers (excepting AbsoluteLayout)

Upvotes: 3

Tony
Tony

Reputation: 1419

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.

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

Upvotes: 1

Related Questions