0

I am trying to show the form many times here in this example 10 times, Can someone help me in doing it?

In the below example i am showing only button to keep it simple, along with the button i will add other components like textbox etc..., In the below example, i am getting the error- times should be made final. If i make it final then, i wont be able to write times = times - 1.

private void showForm(int times){

    if(times >= 1){
      JButton btn = new JButton("ADD");  
      container.add(btn);
      times = times - 1;

      btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showForm(times);
            }
        });          
    }
}
AGEM
  • 217
  • 2
  • 5
  • 12
  • *"I am trying to show the form many times"* ***Why?*** What user feature does this attempt to provide? As an aside, see [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Oct 08 '12 at 15:24
  • @AndrewThompson The same form details has to be shown - the requirement is like that. The values are also has to be sent to database. Once the form is filled, again the same form is shown until times becomes 0. Some scientific related data has to be filled in the form – AGEM Oct 08 '12 at 15:27
  • *"The same form details has to be shown"* This either needs a single component to show details on each in turn (perhaps with a list of all on one side), or a table to show the details of the collection. There is no reason that I can see from your description, to have more than one frame. – Andrew Thompson Oct 08 '12 at 15:30

2 Answers2

3

Just write it like this:

private void showForm(final int times){

    if(times >= 1){
      JButton btn = new JButton("ADD");  
      container.add(btn);

      btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showForm(times - 1);
            }
        });          
    }
}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
3

If by pressing the button you want new buttons to appear, minus 1 every time (this is what I understand), to actually make it work you also need to add revalidate() and a loop

private void showForm(final int times) {
    if (times >= 1) {
        for (int i=0; i<times; i++) {
            JButton btn = new JButton("ADD");  
            container.add(btn);
            container.revalidate();
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    showForm(times-1);
                }
            });
        }
    }
}

else forget the loop but keep revalidate (or you won't see any visible changes)

Rempelos
  • 1,220
  • 10
  • 18