我正在开发一个项目,我有一个名为HGraphic的类,它扩展了JPanel。这个类有一个名为updateNum的公共方法,它接收一个整数作为参数,并对它进行一些处理,更新一些元素。
这个HGprahic类在我的项目的主类中有一个实例(主类扩展了JFrame)...我需要从主类中调用这个特殊的HGraphic方法,将变量作为参数发送。
问题在于虽然该方法被声明为public,但我无法像往常那样访问正常的hGraphicInstance.method(变量)。
我已经阅读了JPanel文档,但没有找到任何说明你无法访问自定义方法的内容......或者你无法创建setter(另一种做我需要的方式)。
当我实例化HGraphic类时,我使用JComponent类来执行此操作,这可能是原因吗?
您有任何想法或建议吗?我真的很感激这件事有点亮......非常感谢!!!
我放置代码的主要部分:
// CLASS CAUSING THE PROBLEM ------------------
public class HGraphic extends JPanel {
// Attributes
public int numberOfCoincidences = 0;
// Constructor
public HGraphic() {
super(new BorderLayout());
}
public void updateNum(int tmpNum) {
numberOfCoincidences = tmpNum;
}
}
// MAIN FRAME CLASS ----------------------------------
public class HSFrame extends javax.swing.JFrame {
private int newNum = 5;
private JComponent newContentPane;
public HSFrame() {
initComponents();
}
private void initComponents() {
newContentPane = new HGraphic();
// HERE IS WHERE I WOULD LIKE TO ACCESS THE CLASS METHOD
// NetBeans say it does not recognize this method :(
newContentPane.updateNew(newNum);
}
}
再次感谢你!
答案 0 :(得分:5)
因为您的实例(newContentPane
)类型为JComponent
。您需要将其定义为HGraphic
或在方法调用之前将其强制转换。
private ***JComponent*** newContentPane;
需要更改为:
private HGraphic newContentPane;
或在方法调用中:
((HGraphic) newContentPane).updateNum(newNum);