There is a form, on this form there are buttons. They can be 100 and 200, etc. How do I know which button was pressed?

    1 answer 1

    If you create a program with a lot of buttons, surely each button for something is intended, and when нажатии on it, an действие should take действие . Then for each button you need to create a слушателя :

     myButton.addActionListener(e -> { // что будет, если нажать на кнопку }); 

    Or, you can add слушателей only for those buttons for which you want. If you click on a button that does not have a listener, nothing will happen.

    If all your buttons already have слушатели and when you click on them, some actions are already performed, but when you click on some specific buttons from the set you need special actions, you can also add them to the listeners of these buttons. For example, closing the program.

    If you add buttons through an array, for example, like this:

     JPanel myPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); for (int i = 0; i < 100; i++){ myPanel.add(new JButton("Button " + i)); } 

    Then the question arises, why are you doing this? You can add buttons through the cycle, by clicking on which nothing happens (then why are they?), And create the rest separately and add слушателей for them.

    • ! I want to implement sampel like that. I use buttons because there are more possibilities in styling. PS In java newbie - pride
    • the point is that the data will be output from the database, that is, they will be deleted and added, plus a lot of buttons, it is silly to write for each listener - pride