2010-09-01 113 views
0

嗨,大家好我有一個問題讓我很困惑,我有'writeMethod'這是一個Method類,'dpv'是一個propertyDescriptor類型,我通過getWriteMethod()獲取了對象的writeMethod,我現在的問題是如何設置「writeMethod」對一個對象(例如一個JLabel,JButton的)的屬性寫在這裏是我的代碼:使用writeMethod寫入對象的屬性?

if(dpv.getPropertyType().isPrimitive() 
     || dpv.getPropertyType().isInstance("Integer")) 
     { 
      Method writeMethod = dpv.getWriteMethod(); 

      //setWriteMethod(writeMethod);<---------- Not sure about this part (doesn't work) 

      System.out.println(writeMethod); 
      PropertyValue.setEnabled(true); 
      SetButton.setEnabled(true); 
     } 
     else{ 

      PropertyValue.setEnabled(false); 
      SetButton.setEnabled(false); 
     } 

感謝您的幫助球員

回答

1

要使用的方法編寫這個propery,你必須調用它。簡單的屬性採用一個值 - 屬性的值,所以你用一個參數調用該方法。下面的代碼設置按鈕上的屬性值42:

Method writeMethod = dpv.getWriteMethod();  
JButton button = ...; // the target to write to 

try 
{ 
    writeMethod.invoke(button, 42); 
} 
catch (IllegalAccessException ex) 
{ 
    // handle these as appropriate 
} 
catch (IllegalArgumentException ex) 
{ 
} 
catch (InvocationTargetException ex) 
{ 
} 

這是不太可能你有他們,但如果該屬性是很少使用的索引屬性類型,那麼你需要使用的方法是這樣的:

writeMethod.invoke(target, index, propertyValue); 

這相當於setter方法

setIndexProperty(int index, PropertyType value); 
+0

感謝它幫助 – HAMID 2010-09-01 10:27:23