Just a simple GUI application that adjusts its layout and the amount of checkboxes shown based on the users entered data, this principle could also be applied for various other Components in Java GUI programming
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DynamicCheckBox extends JFrame implements ActionListener { private DynamicCheckBox() { super("Dynamic Check Box Tester"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout( new BorderLayout() ); setSize( 200, 300 ); initComponents(); // originall with one } private void initComponents( ) { // Get the first panel setup p1 = new JPanel(); p1.setLayout(new GridLayout( 1, 2) ); input = new JTextField(); btn = new JButton("Go"); btn.addActionListener(this); p1.add( input ); // add our components to first JPanel p1.add( btn ); // this is for a panel of checkboxes // // we will hopefull dynamically set it up p2 = new JPanel(); p2.setLayout( new GridLayout( 1, 1) ); p2.add( new JCheckBox("CheckBox")); this.add( p1, BorderLayout.NORTH ); this.add( p2, BorderLayout.SOUTH ); setVisible(true); } private void updateP2( int noOfCheckBoxes ) { // add our checkBoxes p2.setLayout( new GridLayout( noOfCheckBoxes, 1, 4, 4) ); for ( int i = 0; i < noOfCheckBoxes; i++ ) { //boxes.add( new JCheckBox() ); p2.add( new JCheckBox( "This is " + i )); } //this.add(p2, BorderLayout.SOUTH ); } public void actionPerformed(ActionEvent e) { if ( e.getSource() == btn ) { try { int q = Integer.parseInt( input.getText() ); //this.remove( p2 ); p2.removeAll(); p2.updateUI(); updateP2( q ); } catch (Exception err) { input.setText( err.getMessage() ); return; } } } public static void main(String[] args) { new DynamicCheckBox(); } // components private JPanel p1, p2; private JTextField input; private JButton btn; }
Hope this was helpful
