我正在尝试创建自己的Font Chooser
另一个单独的类(class)class
从我拥有主类(JFrame
应用程序)的文件中,我想访问主 JFrame
的 textArea 对象 ,以便修改其字体属性,但我无法做到这一点,因为 textArea 是一个非静态对象。
为了解决这个问题,我想到了将单独的类(“Font Chooser”)做成一个内部类。这是唯一的解决方案吗?
编辑
Font Chooser
对象在创建主 Frame 之后实例化,实际上实例化是由主 JFrame 类完成的,显然我无法访问主 JFrame 公共(public)成员。
谢谢。
最佳答案
我的主要建议:不要忽视 OOP 实践来解决您的问题,例如使用公共(public)字段等。不要让另一个类直接操作 JTextArea 的状态,无论如何它都应该是私有(private)的。相反,为保存 JTextArea 的类提供一个公共(public) setFont 方法,其他类可以在包含类的有效实例上调用该方法。
public class MyGui {
private JTextArea textarea = .....;
public void setTextAreaFont(Font font) {
textarea.setFont(font);
}
因此,对于要调用此方法的对象,它所需要的只是对 MyGui 类的有效引用,其中有效是这里的关键术语。这可能需要您通过 setter 方法或构造函数参数将引用传递到需要它的对象中。这里不需要使用内部类,根本不需要。
当然,JTextArea 字段永远不应该是静态的,因为这会将所有 OOP 抛到九霄云外,从而使维护、增强或测试代码变得非常困难。
<小时/>编辑
您现在声明:
The "Font Chooser" object is instantiated after the creation of the main Frame, in fact the instantiation is done by the main JFrame class, and apparently I cannot access to the main JFrame public members.
那么是什么阻止您在创建 GUI 类时将其传递到字体选择器中呢?
MyFontChooser myFontChooser = new MyFontChooser(this); // ???
再次请详细说明您的问题。
class MyFontChooser {
private MyGui myGui;
public MyFontChooser(MyGui myGui) {
this.myGui = myGui;
}
// some event caused method
public void changeFont() {
myGui.setTextAreaFont(someFont);
}
关于java - 从另一个单独的类访问公共(public)非静态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24914099/