2016-11-05 58 views
1

我想單擊時獲取SpanButton上的客戶端屬性。它拋出一個NullPointerException。SpanButton客戶端屬性拋出NullPointerException

我用普通按鈕測試了相同的代碼,它工作得很好。我相信那裏可能有一個bug。

這裏是如何從一個準系統項目重現此問題:

Form hi = new Form("Hi World"); 
    Button button = new Button("Button"); 
    button.putClientProperty("id", 100); 

    SpanButton spanButton = new SpanButton("SpanButton"); 
    spanButton.putClientProperty("id", 200); 

    button.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent evt) { 
      int id = (int) evt.getComponent().getClientProperty("id"); 
      System.out.println("Standard Button action listener: id = " + id); 
     } 
    }); 

    spanButton.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent evt) { 
      int id = (int) evt.getComponent().getClientProperty("id"); 
      System.out.println("Span button action listener: id = " + id); 
     } 
    }); 

    hi.addComponent(button); 
    hi.addComponent(spanButton); 
    hi.show(); 

如果單擊該按鈕,輸出打印正確:

標準按鈕的動作監聽:ID = 100

如果您單擊SpanButton,將引發NullPointerException。經過調查,我發現SpanButton getClientProperty(「id」)返回null。

注意:我需要使用SpanButton,因爲它支持可變大小。

回答

1

而不是getComponent()使用正確命名getActualComponent()

JavaDocs解釋:

等同於ActionEvent#getComponent()除了事實是,如果這樣的鉛成分可用的鉛成分將被退回。

這對於諸如MultiButton等組件很重要,它將返回底層按鈕。

相關問題