How To - Dynamically Generate Components


Description:

You can dynamically create virtually every component in Java.

Dynamically Create a JButton

buttonGenerator.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;


public class buttonGenerator {

    // A Dynamic JButton Generator

    public void generateButton(JPanel jPanel, JButton existingButton, String text, String buttonName) {

        JButton newButton = new JButton(buttonName); // Setting the new Buttons' name

        newButton.setText(text);  // Setting Button Text

        /* Adding Button to JPanel - Make sure that this is done before
        setting bounds or the your initialization will be delayed */
        jPanel.add(newButton);

        // .setBounds() specifies the position and size of the component
        newButton.setBounds(existingButton.getX(), existingButton.getWidth(), existingButton.getY(), existingButton.getHeight());

        jPanel.validate(); // Validating the addition of the new button to the JPanel.

        // Adding an ActionListener to the newly created button. This allows you to add code to perform "actions" once the button is clicked.
        newButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Hey there");
            }
        });
    }
}


Implementation in a JFrame Generated Manually By Netbeans:


JFrameGUI.java

import javax.swing.JButton;


public class JFrameGUI extends javax.swing.JFrame {

    public JFrameGUI() {
        initComponents();
        }


    @SuppressWarnings("unchecked")
    //
    private void initComponents() {
    // Code from Components created by Netbeans goes ere
    }

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {
        buttonGenerator gen = new buttonGenerator();
        gen.generateButton(jPanel, btnCreate, "Click Me", "myButtonName", txaOutput);
        }


    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        // GUI generated code by Netbeans goes here

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
                new JFrameGUI().setVisible(true);
            }
        });
    }

    // Variables declaration by Netbeans goes here
}

java_strings.htm