WebBrowser.java: Display HTML file in JEditorPane

本文介绍了一个简单的Java程序,该程序允许用户通过输入URL来加载并显示HTML内容。程序使用了JEditorPane组件来展示网页,并支持键盘输入事件及超链接监听。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(转载)

该程序让客户在文本域输入一个HTML文件的URL,按回车键之后,在编辑窗格内显示该HTML文件.

程序代码如下:// WebBrowser.java: Display HTML file in JEditorPane
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.net.URL;
import javax.swing.event.*;
import java.io.*; public class WebBrowser extends JApplet
implements ActionListener,HyperlinkListener{
// JEditor pane to view HTML files
private JEditorPane jep=new JEditorPane();
// Label for URL
private JLabel jlblURL=new JLabel("URL");
// Text field for entering URL
private JTextField jtfURL=new JTextField();

// Initialize the applet
public void init(){
    // Create a panel jpURL to hold the label and text field
    JPanel jpURL=new JPanel();
    jpURL.setLayout(new BorderLayout());
    jpURL.add(jlblURL,BorderLayout.WEST);
    jpURL.add(jtfURL,BorderLayout.CENTER);
    
    // Create a scroll pane to hold JEditorPane
    JScrollPane jspViewer=new JScrollPane();
    jspViewer.getViewport().add(jep,null);
    
    // Place jpURL and jspViewer in the applet
    this.getContentPane().add(jspViewer,BorderLayout.CENTER);
    this.getContentPane().add(jpURL,BorderLayout.NORTH);   // Set jep noneditable
    jep.setEditable(false);
    
    // Register listener
    jep.addHyperlinkListener(this);
    jtfURL.addActionListener(this);
} public void actionPerformed(ActionEvent e){
    // TODO: Implement this java.awt.event.ActionListener method
    try{
      // Get the URL from text field
      URL url=new URL(jtfURL.getText().trim());
      // Display the HTML file
      jep.setPage(url);
    }catch(IOException ex){
      System.out.println(ex);
    }
} public void hyperlinkUpdate(HyperlinkEvent e){
   // TODO: Implement HyperlinkListener method
   try{
      // Get the URL from text field
      jep.setPage(e.getURL());
    }catch(IOException ex){
      System.out.println(ex);
    }
}

// Main method
public static void main(String[] args){
    // Create a frame
    JFrame frame=new JFrame("Web Browser");
    // Create an instance of the applet
    WebBrowser applet=new WebBrowser();
    // Add the applet instance to the frame
    frame.getContentPane().add(applet,BorderLayout.CENTER);
    // Invoke init() and start()
    applet.init();
    applet.start();
    // Display the frame
    frame.setSize(600,600);
    // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}
}不足:该程序不能浏览本地的HTML文件.只能浏览远程的HTML文件,且必须输入以http://开头的URL.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值