![](/img/trans.png)
[英]Is it possible to add a image in JFrame but the class is extended with JPanel?
[英]Swing - Methods and attributes of an extended JPanel class inaccessible from JFrame
我正在一个项目中,我有一个名为HGraphic的类,该类扩展了JPanel。 此类具有一个称为updateNum的公共方法,该方法接收一个整数作为参数并对其进行一些处理,从而更新某些元素。
这个HGprahic类在我的项目的主类中有一个实例(主类扩展了JFrame)...我需要从主类调用HGraphic的此特定方法,并将变量作为参数发送。
问题是,尽管该方法被声明为public,但我无法像往常一样通过正常的hGraphicInstance.method(variable)来访问它。
我遍历了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);
}
}
再次感谢你!
因为您的实例( newContentPane
)类型是JComponent
。 您需要将其定义为HGraphic
或在方法调用之前进行HGraphic
。
private ***JComponent*** newContentPane;
需要更改为:
private HGraphic newContentPane;
或在您的方法调用中:
((HGraphic) newContentPane).updateNum(newNum);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.