문제

이 웹 사이트를 많이 사용하지만 처음 게시하십시오. 내 프로그램은 파일의 레코드 수에 따라 여러 버튼을 만듭니다. 예를 들어 5 개의 레코드, 5 개의 버튼.

버튼이 생성되고 있지만 액션 리스너에 문제가 있습니다.

루프에 액션 리스너를 추가하면 모든 버튼은 같은 작업을 수행합니다. 그러나 루프 외부에 액션 리스너를 추가하면 액션 리스너를 마지막 버튼에 추가합니다.

어떤 아이디어?

여기에 코드가있는 것이 있습니다 (공간을 절약하기 위해 For Loop을 추가했습니다).

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++;
}

매우 감사

도움이 되었습니까?

해결책

생성하는 각 버튼에 대해 하나의 액션 리스너를 만들 때 다음을 수행 할 수 있습니다.

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

익명 클래스 메소드 내부의 변수에 액세스하려면 최종적으로 표시되어야합니다. 그게 당신이 가진 것입니다 final int buttonIndex = i; 성명.

당신은 사용할 수 있습니다 setActionCommand 버튼의 메소드에서 검색 할 수있는 조치 명령을 정의하는 메소드 ActionCommand 의 속성 ActionEvent 수업. 그렇게함으로써 모든 버튼에 대해 동일한 리스너를 가질 수 있습니다. 해당 조치 명령을 다음으로 설정할 수 있습니다 buttonIndex 내가 당신의 예에서 정의한 변수입니다. 이렇게하면 응용 프로그램에서 익명의 클래스가 적습니다. 항상 양호합니다 (메모리가 적은 객체가 적습니다).

다른 팁

버튼 참조 및 색인을 추가 할 수 있습니다 (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's index
            Integer index = map.get( ae2.getSource() );

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

루프 외부에서 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]);
}

그러나 경고, 나는이 코드를 테스트하지 않았다.

첫 번째 문제는 변수에 대한 의존과 함께 있습니다 j.

모든 버튼을 정확히 동일한 ActionListener로 할당하므로 인덱스에서 객체를 인쇄합니다. j, 버튼이 표시되는 시점에 == 인상시 목록의 마지막 인덱스, 목록 namesA.

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();
                }
                });
               }
            }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top