0

我正在创建许多事件处理程序并保持清洁,而不是为可能成为每个处理程序中的源的 20 多个对象拥有大量 if...else,我正在尝试使用 switch-案子。当然,问题是您不能打开一个对象,即 event.getSource(); 返回,然后使用 .toString() 返回任何可以轻松用于每种情况的内容。我想知道是否有办法在字符串中获取事件源对象的名称,可以在开关中使用。按钮的文本,而不是它的名称,也可以工作,但我也在尝试用文本框来做到这一点,在这种情况下,只有名称才能真正起作用。我只遇到了一种解决方案,但由于某种原因它不起作用。

public class EntryHandler implements ActionListener 
{
    @Override
    public void actionPerformed( ActionEvent event ) 
    {
        if( event.getSource() == addEntryButton ) 
        {
            Object source = event.getSource();
            String bString;
            if (source instanceof JButton)
            {
                bString = ((JButton) source).getName();
            } else { 
                bString = "Wrong";
            }
            System.out.printf("b name: %s", bString);
            entryData.addTableEntry();
        }  ... more if's for other buttons...

出于某种原因,这总是打印“b name: null”

我总是可以只使用 if...else 堆栈,这就是它当前的实现方式,但它看起来像一个巨大的混乱。任何建议或替代方案将不胜感激。

4

1 回答 1

-1

You need to use setName() for the component form which you are getting an event. Then you will not get null value instead you will get whatever you will set. For example :

JButton jButton =new JButton();
jButton.setName("name");

On the other side when you get event:

event.getSource().getName();
于 2018-10-07T03:04:10.320 回答