Java 尝试将switch case与actionlistener一起使用
我想知道是否有任何方法可以将switch语句与actionListener一起使用,而不是if-else语句 我尝试了两件事: 1)尝试使用ae.getSource()作为开关Java 尝试将switch case与actionlistener一起使用,java,Java,我想知道是否有任何方法可以将switch语句与actionListener一起使用,而不是if-else语句 我尝试了两件事: 1)尝试使用ae.getSource()作为开关 public void actionPerformed(ActionEvent ae) { switch(ae.getSource()) { case b1: //statement break; } } 我发现这显然不起作用,因为ae.
public void actionPerformed(ActionEvent ae)
{
switch(ae.getSource())
{
case b1:
//statement
break;
}
}
我发现这显然不起作用,因为ae.getSource()将返回该对象
2)尝试将ae.getSource()值转换为字符串
public void actionPerformed(ActionEvent ae)
{
String src = ae.getSource().toString();
switch(src)
{
case "b1":
//statement
break;
}
}
这也不管用,但我觉得值得一试。那么,我有什么办法可以做到这一点,或者我应该依靠可靠的人,如果有其他办法的话。你可以这样使用它(因为它对我有用)
显示if/else版本。@shmosel if/else版本是标准版本,我只使用if(ae.getSource==b1)不能打开
对象。toString()
返回什么?@shmosel返回这个“javax.swing.JButton[,72,30,56x26,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource”$CompoundBorderUIResource@4d52d718,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverSelectedIcon=,rolloverSelectedIcon=,selectedIcon=,text=Add,defaultCapable=true]“我没想到哈哈。我想你必须坚持if/else。
public void actionPerformed(ActionEvent ae)
{
switch(ae.getActionCommand())
{
case "b1":
//statement
break;
}
}