多个组件的方法无效
Posted
技术标签:
【中文标题】多个组件的方法无效【英文标题】:Invalid method for multiple components 【发布时间】:2012-12-30 13:49:06 【问题描述】:代码已大大简化,仅突出显示问题。我也不确定这是否是解决此问题的最佳方法。
我正在尝试制作一个对象,该对象可以具有任何单个摆动组件和一组通用方法来编辑该组件。在这种情况下,如果组件是 JLabel,则具有设置组件文本并返回是否成功的方法。
package table;
import java.awt.Component;
public class CompTest
private Component comp;
public CompTest(Component C)
comp=C;
public boolean setText(String S)
if(comp instanceof javax.swing.JLabel)
comp.setText(S); //error
return true;
return false;
对象的创建方式类似于;
...
CompTest comp1=new CompTest(new javax.swing.JLabel());
...
我正在使用 Netbeans IDE 7.2,并且在包含“//error”的行(在第一个代码块中)给我一个错误;
cannot find symbol
symbol: method setText(String)
location: variable comp of type Component
我该如何解决这个问题,如果没有(我怀疑)我如何让 Netbeans 玩得更好?
【问题讨论】:
【参考方案1】:Component
类没有名为 setText
的方法。
您必须先将comp
转换为 JLabel,然后才能调用该方法,例如:
((javax.swing.JLabel)comp).setText(S);
【讨论】:
【参考方案2】:投给JLabel
((javax.swing.JLabel)comp).setText(S);
【讨论】:
【参考方案3】:因为comp.setText(S); //error
不可用
试试comp.setName()
【讨论】:
comp.setName()
不等同于((JLabel)comp).setText()
。 OP 忘记投射了。以上是关于多个组件的方法无效的主要内容,如果未能解决你的问题,请参考以下文章
React + Antd + Rollup 组件库“错误:无效的钩子调用。钩子只能在函数组件的主体内部调用”