【问题标题】:Swing and WebEditorKit - Showing my browser in a SwingFrameSwing 和 WebEditorKit - 在 SwingFrame 中显示我的浏览器
【发布时间】:2012-03-23 01:28:14
【问题描述】:

我最近一直在做一个小项目,我似乎很困惑自己,遇到了一个巨大的心理障碍。我知道这应该很简单,这就是为什么这让我如此烦恼,但正如标题所示,我有 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 文档的窗口,然后在窗口顶部还有一个菜单,但我什至无法获得目前要显示的浏览器(:()非常感谢任何帮助,因为我现在的头脑很好,真的在泥泞中游泳,我想是时候喝茶了。

【问题讨论】:

    标签: java swing components


    【解决方案1】:

    让你的浏览器框架扩展 javax.swing.JPanel 然后说,

    mainFrame.getContentPane().add(new BrowserFrame());
    

    然后在 BrowserFrame 的构造函数中

    setLayout(new BorderLayout());
    add(jEditorPane);
    

    使用SwingUtilities.invokeLater创建JFrame并在main方法中显示。

    【讨论】:

    • 你是个绝对的英雄,多亏了你,我现在只是在添加 browserFrame 的方式上很愚蠢
    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2012-11-15
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2012-03-08
    相关资源
    最近更新 更多