Java Swing和WebEditorKit-在SwingFrame中显示我的浏览器
我最近一直在做一个小项目,我似乎把自己搞糊涂了,遇到了巨大的心理障碍。我知道这应该很简单,这就是为什么这让我如此恼火的原因,但正如标题所示,我有3门课: main-这应该实例化其他类,并且只真正包含构造函数:Java Swing和WebEditorKit-在SwingFrame中显示我的浏览器,java,swing,components,Java,Swing,Components,我最近一直在做一个小项目,我似乎把自己搞糊涂了,遇到了巨大的心理障碍。我知道这应该很简单,这就是为什么这让我如此恼火的原因,但正如标题所示,我有3门课: main-这应该实例化其他类,并且只真正包含构造函数: import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JFrame; public class main { public static void main(String[] ar
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成为一个组件,但我一辈子都无法解决如何做到这一点,而且它在web上搜索的资源都应用于其他示例代码,因此它最终会让我更加困惑
我想要实现的是,当你运行应用程序打开时,你会看到一个显示我的HTML文档的窗口,然后在窗口的顶部还有一个菜单,但我现在甚至不能让浏览器显示(:()非常感谢您的任何帮助,因为我的大脑目前正在泥泞中畅游,我想是喝杯茶的时候了。让您的浏览器框架扩展javax.swing.JPanel,然后说
mainFrame.getContentPane().add(new BrowserFrame());
然后在BrowserFrame的构造函数中
setLayout(new BorderLayout());
add(jEditorPane);
使用
SwingUtilities.invokeLater
创建JFrame并在main方法中显示它。你是一个绝对的英雄,现在解决了,多亏了你,我只是在添加浏览器框架的方式上太愚蠢了