代码已被大大简化,仅突出显示问题。我也不确定这是否是解决此问题的最佳方法。
我正在尝试创建一个可以具有任何单个 Swing 组件和一组编辑该组件的通用方法的对象。在本例中,如果组件是 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 正常运行?
最佳答案
类 Component
没有名为 setText
的方法。
您必须首先将 comp
转换为 JLabel,然后才能调用该方法,例如:
((javax.swing.JLabel)comp).setText(S);
关于java - 多个组件的方法无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14355086/