Getting the name of a JButton on click

我只是一个虾纸丫 提交于 2019-12-06 05:46:22

You can cast to a JComponent if you know that only JComponents will be the return value of e.getSource() I'm using JComponent as the cast since it gives more flexibility. If you're only using JButtons, you can safely cast to a JButton instead.

  @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == thirdBtn) {
                    //System.out.println("Third Button Click");
                    System.out.println(((JComponent) e.getSource()).getName()+" Click");
                }
            }

Feel free to replace getName() with getText(), depending on what exactly you need.

Also, the == operator should only be used to compare Object references, so consider casting to a JComponent from the beginning and using .equals() on the names or text.

Edit You can't output the name of the variable, but you can set the name/text of the JComponent. Eg

JButton btnExample = new JButton();
btnExample.setName("btnExample");

Or if you want "btnExample" to actually be displayed on the button:

JButton btnExample = new JButton();
btnExample.setText("btnExample");
System.out.println(((JButton) e.getSource()).getName() + " Click");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!