2011-08-14 23 views
0

我需要將LookAndFeel接口的副本序列化到文件中。因此,我已經寫了下面的代碼:可序列化的LookAndFeel - ClassCastException

public class SerializableLookAndFeel extend LookAndFeel implement Serializable { 
    public String getID() { 
     return ""; 
    } 
    public String getDescription() { 
     return ""; 
    } 
    public String getName() { 
     return ""; 
    } 
    public boolean isSupportedLookAndFeel() { 
     return false; 
    } 
    public boolean isNativeLookAndFeel() { 
     return false; 
    } 
} 

在運行時,我得到

異常在線程 「主要」 java.lang.ClassCastException: javax.swing.plaf.metal.MetalLookAndFeel中不能轉換爲 test.SerializableLookAndFeel

我試圖擴大MetalLookAndFeel,但在運行時我得到ClassCastException異常。

我如何設法序列化LookAndFeel文件呢?

回答

1

首先,我承擔這是一個錯字,你的意思是extends而不是extendLookAndFeel類有2個直接已知小類BasicLookAndFeelMultiLookAndFeel

您的例外情況表明您正試圖將MetalLookAndFeel轉換爲SerializableLookAndFeel。您的SerializableLookAndFeel延伸了LookAndFeel,而MetalLookAndFeel延伸了BasicLookAndFeel。實際上,你試圖將兄弟姐妹的孩子分配給你的班級,這是行不通的。

嘗試擴展BasicLookAndFeel如果問題仍然存在,請嘗試發佈您的測試代碼。

+0

我想要做的是從我的電腦中獲取當前的外觀,並使應用程序在每次啓動時加載此設置。所以,我決定把它保存爲一個二進制對象。但是,有一個問題需要你做的建議 - 你不能做像BasicLookAndFeel lookAndFeel = UIManager.getLookAndFeel(); IDE不會讓我去。 – ilja

+0

'UIManager.getLookAndFeel()'返回一個Abstract類的LookAndFeel。所以你的代碼應該工作,你有沒有嘗試過鑄造? 'BasicLookAndFeel lookAndFeel =(BasicLookAndFeel)UIManager.getLookAndFeel();'你在用什麼IDE?你可以發佈我可以運行的代碼嗎?如果沒有看到代碼,我無法得到很多幫助。另外,如果問題仍然存在,請查看調試器並查看getLookAndFeel()返回的結果。 – Ali

+0

public static void main(String [] args)throws Exception JFrame frame = new JFrame(「Test」); frame.setSize(600,400); TextArea textArea = new TextArea(20,10); frame.add(textArea); frame.setVisible(true); BasicLookAndFeel blaf =(BasicLookAndFeel)UIManager.getLookAndFeel(); s(blaf); (BasicLookAndFeel blaf){ 嘗試FileOutputStream fout = new FileOutputStream(「basiclook.dat」); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(basicLookAndFeel); oos.close(); (例外e){ e.printStackTrace(); } }' java.io.NotSerializableException:java.lang.Object.I use IDEA – ilja

1

1)只是錯字:-)不extend LookAndFeelextends LookAndFeel

2)不是好主意Set the Look and Feel作爲參數,確保你方信用證& F改變必須是:

try { 
    UIManager.setLookAndFeel(laf[index].getClassName()); 
    SwingUtilities.updateComponentTreeUI(frame); 
    //or SwingUtilities.windowForComponent(myComponent) 
} catch (Exception exc) { 
    exc.printStackTrace(); 
} 
+0

1)在實際代碼中沒有錯別字 - 就在這裏。問題仍然是實際的 – ilja

1

你在做奇怪的事情。你的SerializableLookAndFeel是(有點)MetalLookAndFeel的兄弟姐妹,所以演員不能工作。

MetalLookAndFeel延伸BasicLookAndFeel延伸LookAndFeel並實現Serializable,所以有再次加Serializable沒有意義的。

簡單地嘗試序列化它是什麼?怎麼了?

你真的需要序列化看看&的感覺嗎?不會簡單地保存它的名字(或其他)嗎?

+0

請參閱MetalLookAndFeel lookAndFeel = UIManager.getLookAndFeel(); – ilja

相關問題