gpt4 book ai didi

java - 关于StyledDocument和JTextPane的关系以及接口(interface)的正确使用问题

转载 作者:行者123 更新时间:2023-12-01 11:15:55 26 4
gpt4 key购买 nike

我是java新手,正在研究java swing GUI。最近读到一篇帖子: Centering Text in a JTextArea or JTextPane - Horizontal Text Alignment

里面的解决方案工作得很好,但我有一些概念性问题要问。

我在oracle网站上看了接口(interface)和类的介绍。它表示该接口(interface)包含一组空体方法,那么实现该接口(interface)的类需要声明该接口(interface)中提到的所有方法才能成功编译。

我的问题来了:看完文档,我知道StyledDocument是一个接口(interface),但是下面的代码是什么意思呢?

StyledDocument doc = textPane.getStyledDocument();

我的解释是,我猜 JTextPane 在内部实现了 StyledDocument,因此这行代码将接收现有的 StyledDocument (但它不应该被称为实例,因为我们无法创建接口(interface)实例,我该如何描述它?)。如果这是真的,那么 JTextPane 应该具有在 StyledDocument 接口(interface)中定义的所有方法。

我在上面的段落中正确吗?

然后,我尝试不写这两行代码:

StyledDocument doc = textPane.getStyledDocument();
doc.setParagraphAttributes(0, doc.getLength(), center, false);

但是我直接使用了:

textPane.setParagraphAttributes(center, false);

这也很有效。

那么,这两种实现之间有什么区别吗?

我的代码是这样做的好习惯吗?

非常感谢您的帮助!

最佳答案

我认为您陷入了多态性的概念,看看 Polymorphism 上的踪迹对于初学者。

My interpretation is that, I guess that a JTextPane implements the StyledDocument internally so that this line of code is to receive the existing StyledDocument (But it should not be called an instance as we could not create instance of interface, How should I describe it?). If this is true, then JTextPane should have all methods defined in the StyledDocument interface.

没有。 getStyledDocument 方法返回一个实现 StyledDocument 接口(interface)的对象。 JTextPane 不直接实现此功能,而是将要求委托(delegate)给实现 StyledDocument 接口(interface)的对象实例。

它们共同提供了显示样式文本的方法。这是Model-View-Controller的一个概念。范例,其中非可视功能(模型或 StyledDocument)与 View (JTextPane)分离

Then, I tried not to write this two lines of code:

StyledDocument doc = textPane.getStyledDocument();
doc.setParagraphAttributes(0, doc.getLength(), center, false);

But I directly used:

textPane.setParagraphAttributes(center, false);

And this also worked perfectly.

So, are there any differences between the two implementations?

是和否。 setParagraphAttributes 将功能委托(delegate)给 StyledDocument,如下面摘自 JTextPane 的代码片段所示:

public void setParagraphAttributes(AttributeSet attr, boolean replace) {
int p0 = getSelectionStart();
int p1 = getSelectionEnd();
StyledDocument doc = getStyledDocument();
doc.setParagraphAttributes(p0, p1 - p0, attr, replace);
}

它只是一种方便的方法,让您的生活变得更简单

Is my code a good practice to do so?

我认为使用提供的功能来实现您的目标没有问题。

关于java - 关于StyledDocument和JTextPane的关系以及接口(interface)的正确使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31823467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com