2017-04-10 21 views
-1

有没有一种方法来获得与特定命令字符串关联的按钮? 举例来说,如果我定义一个按钮:Java ActionCommand

button.setActionCommand("unique_toggle"); 

有了这样的字符串“unique_toggle”,是有可能从另一类按钮?我是Java的初学者,如果这个问题对你来说可能显而易见,那么这个问题很有借口。

+2

让'其他班'成为动作监听者。在action执行的方法中使用['Ev​​entObject.getSource()'](http://docs.oracle.com/javase/8/docs/api/java/util/EventObject.html#getSource--)。另请参阅[什么是XY问题?](http://meta.stackexchange.com/q/66377),因为这听起来很像。 –

+0

肯定会试试,谢谢 – Alien13

+0

请问EventObject.getSource()能解决我的问题吗?因为我从不按那个按钮。我只有setActionCommand所指的那个按钮。 – Alien13

回答

0

是的,您可以访问您的按钮及其相关按钮的命令。如果你需要一个按钮的命令,这可能意味着你应该考虑重新设计你的程序,因为这种方法是不建议和非常肮脏的方式来做你想达到的。

当谈到回答你的问题,

比方说Foo1是你GUI类。

class Foo1{ 

JButton button; 

public Foo1(Foo2 otherClass) 
{ 
button = new JButton(); 
otherClass.setButtonAddress(button); 
} 
..... other methods 
} 

Foo2是您想要访问按钮的命令文本的类。

class Foo2{ 
JButton buttonFromOtherClass; 

//This is the method, in where you need command string of the button 

private void getCommandsString() 
{ 
Foo1 foo1 = new Foo1(this); 

//After the initialization of Foo1, you can get every information of the button 
    String actionCommand = buttonFromOtherClass.getActionCommand(); 
} 


public void setButtonAddress(JButton button) 
{ 
buttonFromOtherClass = button; 
} 

}