Swingexamples-read-url-to-display-page

提供:Dev Guides
移動先:案内検索

Swingの例-URLを使用してHTMLページを表示する

次の例では、URLを読み取ってそのページをSwingベースのアプリケーションで表示する方法を示します。

次のAPIを使用しています。

  • JEditorPane -HTMLコンテンツを表示するためのエディターボックスを作成します。
  • * jEditorPane.setPage(String url)*-渡されたURLからHTMLを取得して表示します。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 450);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();
      panel.setLayout(layout);

      JEditorPane jEditorPane = new JEditorPane();
      jEditorPane.setEditable(false);
      try {
         jEditorPane.setPage("http://www.google.com");
      } catch (IOException e) {
         jEditorPane.setContentType("text/html");
         jEditorPane.setText("<html>Page not found.</html>");
      }

      JScrollPane jScrollPane = new JScrollPane(jEditorPane);
      jScrollPane.setPreferredSize(new Dimension(540,400));

      panel.add(jScrollPane);
      frame.getContentPane().add(panel, BorderLayout.CENTER);
   }
}

出力

URLを使用してHTMLを表示 link:/cgi-bin/printpage.cgi [__ Print]