使用 Action Listener 获取 JButton 的文本
Get the text of a JButton using a Action Listener
为什么 getText
在代码中显示的动作侦听器中导致 error: cannot find symbol
是有原因的?另外,如果有,我该如何解决这个错误?
class openNewPaneActionListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String butSrcTxt = e.getSource().getText();
}
}
您可以使用一个简单的技巧...
@Override
public void actionPerformed(ActionEvent e)
{
String butSrcTxt = e.getActionCommand();
}
如果您没有为按钮指定 actionCommand
,则使用按钮的 text
。
现在,如果您确实为按钮指定了 actionCommand
属性 并且您仍然想知道文本(这对我来说似乎很奇怪),您可以使用更像...
@Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
String butSrcTxt = btn.getText();
}
}
为什么 getText
在代码中显示的动作侦听器中导致 error: cannot find symbol
是有原因的?另外,如果有,我该如何解决这个错误?
class openNewPaneActionListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
String butSrcTxt = e.getSource().getText();
}
}
您可以使用一个简单的技巧...
@Override
public void actionPerformed(ActionEvent e)
{
String butSrcTxt = e.getActionCommand();
}
如果您没有为按钮指定 actionCommand
,则使用按钮的 text
。
现在,如果您确实为按钮指定了 actionCommand
属性 并且您仍然想知道文本(这对我来说似乎很奇怪),您可以使用更像...
@Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
String butSrcTxt = btn.getText();
}
}