我最近在做一个小项目,我自己似乎很困惑,遇到了很大的心理障碍。我知道这应该很简单,这就是为什么这让我如此烦恼,但正如标题所示,我有 3 个类:
main - 这应该实例化其他类,并且只真正包含构造函数:
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
BrowserFrame browser = new BrowserFrame();
JFrame mainFrame = new JFrame();
mainFrame.setSize(550,550);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Total Guesswork on the next line! Result of a mental block!
//mainFrame.add(browser);
}
}
BrowserFrame - 这是我创建实际 HTML 查看器的地方。
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
public class BrowserFrame {
public BrowserFrame() {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
URL url = null;
try {
url = new URL("file:///C:/PersonalWorkSpace/PrivateEyes/html/test.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
JEditorPane jEditorPane = new JEditorPane();
jEditorPane.setEditable(false);
JScrollPane jScrollPane = new JScrollPane(jEditorPane);
HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("body {color:#000; font-family:times; margin: 4px;}");
styleSheet.addRule("h1 {color: blue;}");
styleSheet.addRule("h2 {color: #ff0000;}");
try {
jEditorPane.setPage(url);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
最后是工具栏,到目前为止它还没有任何内容,但最终将包含我希望在编码后显示在 JFrame 顶部的工具栏。
我知道我需要使 BrowserFrame 成为一个组件,但我一生都无法弄清楚如何做到这一点,并且它在网络上搜索的资源都应用于其他示例代码,所以它最终让我更加困惑!
我想要实现的是,当你运行应用程序打开时,你会得到一个显示我的 HTML 文档的窗口,然后在窗口顶部还有一个菜单,但我什至无法获取目前要显示的浏览器 (:()) 非常感谢任何帮助,因为我的思绪此刻确实在泥浆中游泳,我想是时候喝杯茶了。
最佳答案
让您的浏览器框架扩展 javax.swing.JPanel 然后说,
mainFrame.getContentPane().add(new BrowserFrame());
然后在BrowserFrame的构造函数中
setLayout(new BorderLayout());
add(jEditorPane);
使用 SwingUtilities.invokeLater
创建 JFrame 并在 main 方法中显示它。
关于java - Swing 和 WebEditorKit - 在 SwingFrame 中显示我的浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9568958/