1

I'm trying to generate buttons dynamically and add an ActionListener that put the name of the button into a TextArea. My code is like:

    int numnotas = model.getColumnCount();
    JButton[] notasbot = new JButton[numnotas];

    BotonesNotas.setLayout(new GridLayout());
    for( int k = 1; k < numnotas; k++){
        variables.add(model.getColumnName(k));
        notasbot[k-1]=new JButton(variables.get(k-1));
        notasbot[k-1].setSize(new Dimension(80,23));
        notasbot[k-1].setLocation(80, 350);
        notasbot[k-1].setMargin(new Insets(2,14,2,14));
        notasbot[k-1].setAlignmentX(0);
        notasbot[k-1].setAlignmentY(1);
        notasbot[k-1].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        notasbot[k-1].setVerticalAlignment(javax.swing.SwingConstants.CENTER);
        notasbot[k-1].addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent e) {
                entrada.insert(????,entrada.getSelectionEnd());
            }
        });
        notasbot[k-1].setLayout(null);
        BotonesNotas.add(notasbot[k-1]);
        notasbot[k-1].setVisible(true);
    }

What can I set in ???? to get the name of the button. If I put something like "notasbot[k-1].getName()" it's give me an error: local variable k is accessed from within inner class; needs to be declared final

What should I do ? Thanks

4

1 回答 1

3

You can use the ActionEvents getSource method. Here you would do:

JButton eventSourc = (JButton)e.getSource();

inside of your actionPerformed method.

于 2013-03-05T22:09:10.977 回答