Having a different action for each button dynamically created in a loop

use this site a lot, but publish it first. My program creates several buttons depending on the number of entries in the file. For instance. 5 entries, 5 buttons.

Buttons are created, but I have a problem with the action listener.

If you add an action performer in a loop, each button does the same; but if I add an action listener outside the loop, it just adds an action listener to the last button.

Any ideas?

Here is what I have in the code (I just added a for loop to save space):

int j=0;
for(int i=0; i<namesA.size(); i++)
{
    b = new JButton(""+namesA.get(i)+"");
    conPanel.add(b);
    conFrame.add(conPanel);

    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae2){

                System.out.println(namesA.get(j));

        }
    }});
    j++;
}

Significant score

+3
source share
5 answers

, :

final int buttonIndex = i;
b.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent ae2) {
       System.out.println("Button pressed is: " + buttonIndex);
   }
}

, final. , , final int buttonIndex = i;.

setActionCommand , , actionCommand ActionEvent. , . buttonIndex, . , , ( ).

+2

(i) .

, .

- (-, PLS , ):

Hashmap<JButton, Integer> map = new Hashmap<JButton, Integer>();

int j=0;
for (int i = 0; i < namesA.size(); i++)
{
    b = new JButton("" + namesA.get(i) + "");
    conPanel.add(b);
    conFrame.add(conPanel);

    // Add a mapping
    map.add(b, new Integer(i));

    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae2) {
            // Look up the button in the map, and get it index
            Integer index = map.get( ae2.getSource() );

            // Do something different here based upon index
        }
    });
    j++;
}
+2

ActionListeners , actionListener , . - :

ActionAdapter[] listeners = new ActionAdapter[namesA.size()];
//fill listeners with ActionAdapters
listeners[0] = new ActionAdapter() 
{
    public void actionPerformed(ActionEvent e) {
        //Do stuff
    }
};
//Repeat for each button you need

for(int i = 0; i < namesA.size(); i++)
{
    b = new JButton("" + namesA.get(i) + "");
    conPanel.add(b);
    b.addActionListener(listeners[i]);
}

, , .

+1

j.

You assign the same ActionListener to all buttons, which will print the object by index j, which when the == buttons are displayed is the last index of the list during increments of the list namesA.

0
source
public class Scroll_view extends Activity {

Button btn;
Button btn1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scroll_view);



        LinearLayout linear=(LinearLayout)findViewById(R.id.linear);
        for(int i=1; i<=20 ;i++){
            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            btn=new Button(this);
            btn.setId(i);
            final int id_=btn.getId();
            btn.setText("button " + id_);
            linear.addView(btn,params);


            btn1=((Button)findViewById(id_));
            btn1.setOnClickListener(new View.OnClickListener(){         
                public void onClick(View view){
                    Toast.makeText(view.getContext() , "Button clicked index = " + id_ , Toast.LENGTH_SHORT).show();
                }
                });
               }
            }
}
0
source

Source: https://habr.com/ru/post/1736590/


All Articles