swing 嵌入html
时间: 2023-08-17 07:09:26 浏览: 96
在 Swing 中嵌入 HTML,可以使用 JEditorPane 或者 JTextPane 组件来实现。这两个组件都支持显示 HTML 内容。
下面是一个简单的示例代码,演示如何在 Swing 中嵌入 HTML:
```java
import javax.swing.*;
import java.awt.*;
public class HTMLSwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("HTML Swing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建一个 JEditorPane 组件
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
// 设置 JEditorPane 的内容类型为 text/html
editorPane.setContentType("text/html");
// 加载并显示 HTML 内容
String htmlContent = "<html><body><h1>Hello, <i>Swing</i>!</h1></body></html>";
editorPane.setText(htmlContent);
// 将 JEditorPane 添加到 JFrame
frame.getContentPane().add(new JScrollPane(editorPane), BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
```
运行以上代码,将会显示一个包含 HTML 内容的 Swing 窗口。在这个例子中,我们将内容类型设置为 text/html,然后将 HTML 字符串作为文本设置给 JEditorPane 组件。
你可以根据需要在 HTML 中添加样式、图像和超链接等内容。