001 package org.springframework.richclient.widget; 002 003 import org.springframework.core.io.Resource; 004 import org.springframework.util.FileCopyUtils; 005 006 import javax.swing.*; 007 import javax.swing.text.html.HTMLEditorKit; 008 import java.awt.*; 009 import java.io.BufferedReader; 010 import java.io.IOException; 011 import java.io.InputStreamReader; 012 013 /** 014 * HTMLViewingWidget generates a component to view HTML data 015 * 016 * {@inheritDoc} 017 * 018 * @see #setContent(org.springframework.core.io.Resource) 019 * @see #setContent(String) 020 */ 021 public class HTMLViewWidget extends AbstractWidget 022 { 023 /** Pane in which the HTML will be shown. */ 024 private JTextPane textPane; 025 026 /** Complete component with scrollbars and html pane. */ 027 private JComponent mainComponent; 028 029 private boolean hasContent; 030 031 public HTMLViewWidget() 032 { 033 this(false); 034 } 035 036 public HTMLViewWidget(boolean readOnly) 037 { 038 this.textPane = new JTextPane(); 039 this.textPane.setEditorKit(new HTMLEditorKit()); 040 this.textPane.setEditable(!readOnly); 041 042 JScrollPane scrollPane = new JScrollPane(this.textPane); 043 scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); 044 scrollPane.setPreferredSize(new Dimension(250, 155)); 045 046 // below is a small lie to make sure we provide a blank control in case 047 // people create us without ready content 048 this.hasContent = true; 049 050 this.mainComponent = scrollPane; 051 } 052 053 public HTMLViewWidget(Resource resource) 054 { 055 this(); 056 setContent(resource); 057 } 058 059 public HTMLViewWidget(Resource resource, boolean readOnly) 060 { 061 this(readOnly); 062 setContent(resource); 063 } 064 065 public HTMLViewWidget(String htmlText) 066 { 067 this(); 068 setContent(htmlText); 069 } 070 071 public HTMLViewWidget(String htmlText, boolean readOnly) 072 { 073 this(readOnly); 074 setContent(htmlText); 075 } 076 077 public void setContent(Resource resource) 078 { 079 080 String text = null; 081 try 082 { 083 if (resource != null && resource.exists()) 084 { 085 text = FileCopyUtils.copyToString(new BufferedReader(new InputStreamReader(resource 086 .getInputStream()))); 087 } 088 } 089 catch (IOException e) 090 { 091 logger.warn("Error reading resource: " + resource, e); 092 throw new RuntimeException("Error reading resource " + resource, e); 093 } 094 finally 095 { 096 setContent(text); 097 } 098 } 099 100 public void setContent(String htmlText) 101 { 102 this.textPane.setText(htmlText); 103 this.hasContent = (htmlText != null && htmlText.length() > 0); 104 } 105 106 public JComponent getComponent() 107 { 108 return this.hasContent ? this.mainComponent : new JPanel(); 109 } 110 } 111