简体   繁体   中英

Java jbutton in an arraylist, how can i know which one is clicked

I have two arraylists with the same size, one for JButton, one for JTextField. When clicking the button, the corresponding textfield should be updated. How can I realize that?

ps the number of jcomponents pairs (jbutton + jtextfield) are not fixed. They are designed to be added or removed by the user. However, they have to be in the fixed order.

    ArrayList<JButton> buttonList = new ArrayList<JButton>();
    ArrayList<JTextField> textFieldList = new ArrayList<JTextField>();

    private JButton createButton(){
    JButton button = new JButton("Choose File");
    buttonList.add(button);
    button.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    textField = textFieldList.get(i)
                    textField.setText("show updats");
                }
            }       
    );      
    return button;
}

How can I know the index "i" in the JButton ArrayList?

The ActionEvent has a source , which will be the JButton that is firing the event.

public void actionPerformed(ActionEvent event) {
    int i = buttonList.indexOf(event.getSource());
    .
    .
    .
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM