新手问题:如何从同一个类中的另一个方法访问创建的 JComboBox 实例,否则
如果我有:
A 类{
// 这里有一堆东西 公共无效初始化(){ // 这里有一堆东西 JComboBox jBox = new JComboBox() formatBox.addItem(//这里添加了一些对象)) //我在这个初始化方法中完成剩下的工作 }
}
如果我想添加另一个在调用时可以在 jBox 上操作的方法,我该怎么做?此代码不起作用:
Class A {
// bunch of stuff here
public void intitialize() {
// bunch of stuff here
JComboBox jBox = new JComboBox()
formatBox.addItem(//some objects added here))
//I do the rest of my business in this intitialize method
}
//newly added method
public void anotherMethod(){
jBox.removeItem(//some item here)
}
}
允许从类或其他类的不同方法访问 jBox 的正确编写方法是什么?为什么它不这样工作?
If I have:
Class A {
// bunch of stuff here public void intitialize() { // bunch of stuff here JComboBox jBox = new JComboBox() formatBox.addItem(//some objects added here)) //I do the rest of my business in this intitialize method }
}
if I want to add another method that when called can operate on jBox how can i do it? this code does not work:
Class A {
// bunch of stuff here
public void intitialize() {
// bunch of stuff here
JComboBox jBox = new JComboBox()
formatBox.addItem(//some objects added here))
//I do the rest of my business in this intitialize method
}
//newly added method
public void anotherMethod(){
jBox.removeItem(//some item here)
}
}
What are the correct ways of writing this that allow jBox to be accessed from different methods of the class or other classes? and why doesn't it work this way ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用实例变量并将
JComboBox
存储在那里。如果您想从另一个类访问它,您可能应该创建一个公共 getJBox() 方法,这样实例方法就可以是私有的。例如:
Use an instance variable and store the
JComboBox
there instead. If you want to access it from another class, you should probably create a publicgetJBox()
method, that way the instance method can be private.For example:
将 JComboBox 定义为 A 类中的字段,并删除
initialize
方法中的类型声明:define the JComboBox as a field in Class A and remove the type declaration inside the
initialize
method: