简体   繁体   English

我如何查看Java中是否已按下装有imageIcon的按钮?

[英]How do I see if a button with an imageIcon loaded has been pressed in java?

I have a program where I have a settings button. 我有一个带有设置按钮的程序。 This button has an image icon which shows an image. 此按钮具有显示图像的图像图标。 Any tips on how I can preform an action when it is pressed. 关于如何在按下操作时执行操作的任何提示。 Here is that code 这是代码

JButton imageButton = new JButton(new ImageIcon("/Users/Sam/Programming/Files/gears.png"));

It works fine. 工作正常。 But when I want to use 但是当我想使用

else if(ae.getActionCommand().equals(imageButton)){//doStuff}

it doesnt work. 它不起作用。 My action preformed method works, here it is 我的动作预设方法有效,在这里

public void actionPerformed(ActionEvent ae)
{}

Your ActionListerner is not responding because getActionCommand() should return a String. 您的ActionListerner没有响应,因为getActionCommand()应该返回一个String。 In this case it should be the name of the JButton. 在这种情况下,它应该是JButton的名称。

 else if(ae.getActionCommand().equals(imageButton.getText())){//doStuff}

Changing it to imageButton.getText() should solve the problem. 将其更改为imageButton.getText()应该可以解决此问题。

If you are not sure, just manually set the ActionCommand through setActionCommand() and use the same String to verify getActionCommand in the .equals() method. 如果不确定,只需通过setActionCommand()手动设置ActionCommand并使用相同的String来验证.equals()方法中的getActionCommand。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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