This code will not work as you expect because with each iteration of the loop, you create a spinner and a related button, but in the next iteration, it loses any reference to the ones that were created in the previous iteration.
The use of variables with a very wide scope inside the loop only makes the situation worse because only the button and the spinner of the last iteration will be stored. For this reason, all buttons reflect only what is marked in the last spinner.
The simplest solution would be to store the spinners and buttons in arrays, and use their index to be able to identify them in the listener. Remembering that since it has the same number of buttons and spinners, I used the button index to identify the related spinner:
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
public class Minimo extends JFrame {
JSpinner[] spinners = new JSpinner[10];
JButton[] botoes = new JButton[10];
JScrollPane scrollPane = new JScrollPane();
JPanel panel = new JPanel(new GridLayout(0, 2));
public Minimo() {
super("Produtos em Estoque");
for (int i = 0; i < 10; i++) {
JSpinner spinner = new JSpinner();
JButton botao = new JButton();
botao.setActionCommand(String.valueOf(i));
botao.addActionListener(e -> {
JButton btn = (JButton) e.getSource();
int index = Integer.valueOf(btn.getActionCommand());
JOptionPane.showMessageDialog(null, "Valor do spinner " + (index+1) + ": " + spinners[index].getValue());
});
spinners[i] = spinner;
botoes[i] = botao;
panel.add(botao);
panel.add(spinner);
}
add(panel);
setVisible(true);
setSize(1360, 720);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Minimo::new);
}
}
In the code above, I also used setActionCommand()
in the buttons, because you need to pass a fixed indexing to the listener, otherwise there will be the same problem of always catching the last one. With this command, I record the index on each button, so when it passes the listener, it will get the correct index of the spinner from which that button is relative.
Another error in your code is not setting the behavior of the window when it is closed. By default, the window is only hidden, running in the background, you need to change this behavior otherwise the user of your application will not be able to open the window a second time, unless you restart the computer. So I added the line setDefaultCloseOperation(EXIT_ON_CLOSE);
in the code, it causes the window to be closed, closing the application correctly.
Finally, you are not forwarding your application to the
31.08.2018 / 18:31