![](/img/trans.png)
[英]How to access class loaded by classloader in lower hierarchy from class in higher up hierarchy
[英]How to get an object of a class lower in a class hierarchy
我試圖通過使用getComponentAt()
方法使用點對象(移動)從GridLayout
獲取JButton
。 通過使用gridlayout的框架,我可以進行以下調用:
JButton button2 = frame.getComponentAt(move);
麻煩的是這兩種類型不兼容。 button2是一個JButton,但是frame.getComponentAt(move)
是一個組件。 嘗試編譯時收到以下錯誤消息。
incompatible types
found : java.awt.Component
required: javax.swing.JButton
我知道這兩個來自相同的類層次結構,但是JButton要低得多。 http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html http://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
如何從組件中取出JButton,以便可以指定此按鈕?
您應該將Component強制轉換為JButton:
JButton button2 = (JButton) frame.getComponentAt(move);
您應該首先檢查此Component
是否實際上是JButton
,然后將其轉換為JButton
:
Component c = frame.getComponentAt(move);
if (c instanceof JButton) {
JButton button2 = (JButton) c; // component is a JButton
} else {
... // component is not a JButton
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.