Create Java dynamic form fields without HTML references

292 Views Asked by At

I’ve tried alternative components and codes for form fields such as adding a new panel component when the button ‘Add Another Form’ is pressed. I used GridLayout for the vertical flow of those forms and FlowLayout for the frame. The thing that I wanted to implement is a simple, standard version of this type where it also instantiates it at a specific location on the frame and not the next of the last component added at runtime. Moreover, sets with the scrollpane to flow out the components and not compress it dependent with the container. Here is a sample code for my alternate program:

package sample;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class SampleSubForm_Demo extends JFrame{

    JPanel subP = new JPanel();
    JButton subB = new JButton("Add another");

    public SampleSubForm_Demo(){
        setGUI();

        subB.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0) {
                JPanel jp = new JPanel();
                jp.setBackground(Color.cyan);

                jp.add(new JLabel("Enter something again: "));
                jp.add(new JTextField(4));
                JButton jb = new JButton("Delete this");
                jp.add(jb);             

                jb.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent arg0) {
                        subP.remove(jp);
                        revalid();
                    }

                });

                subP.add(jp);

                revalid();              
            }
        });
        subP.add(subB);
        subP.setLayout(new GridLayout(0,1));

        add(new JLabel("Enter something: "));
        add(new JTextField(20));
        add(subP);

        revalidate();
    }


    private void revalid() {
        subP.revalidate();      
    }

    private void setGUI() {
        setLayout(new FlowLayout());
        setSize(200,200);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args){
        new SampleSubForm_Demo();
    }

}

I’m not that into obvious HTML solutions or any other alternatives but can still provide detailed procedures. Thanks in advance :)

0

There are 0 best solutions below