How to access jtextPane in a different form? - java

I am developing an application where, when I select a value(file) from list it should be opened in jTextPane of a different form. I am using two panels one is mainpanel where my list is shown and one is ExcelSheet, when i click on a list value then mainpanel is closed and new form ExcelSheet is displayed but not the content of doc file in jTextPane.
XWPFWordExtractor extractor=null;
File file=null;
String str=(String) list.getSelectedValue();
mainPanel.setVisible(false);
new ExcelSheet().setVisible(true);
ExcelSheet obj=new ExcelSheet();
try {
file=new File("C:\\Users\\Siddique Ansari\\Documents\\CV Parser\\"+str);
FileInputStream fis=new FileInputStream(file.getAbsolutePath());
XWPFDocument document=new XWPFDocument(fis);
extractor = new XWPFWordExtractor(document);
String fileData = extractor.getText();
Document doc = obj.jTextPane1.getDocument();
System.out.println(fileData);
doc.insertString(doc.getLength(), fileData, null);
}
catch(Exception exep){exep.printStackTrace();}

Use Action to encapsulate the code that updates the text pane in order to display a given file. You can invoke the action from a ListSelectionListener added to your JList. You can also use the action in a menu item or a toolbar button, as shown here. ImageApp is a related example.
For example, each instance of your action will need the target text pane and file:
class FileAction extends AbstractAction {
JTextPane target;
File file;
public FileAction(JTextPane target, File file) {
this.target = target;
this.file = file;
}
#Override
public void actionPerformed(ActionEvent e) {
// render file in target
}
}

Related

How to open a generated PDF in vaadin?

In my vaadin application I have a Table with an additional column containing a print Button. The Button calls the following util method to create a pdf and open it in a new window (ui parameter is the button):
public static void printPDF(Offer offer, AbstractComponent ui) throws IOException, DocumentException, TemplateException {
// ... create PDF
FileResource resource = new FileResource(pdfFile);
BrowserWindowOpener opener = new BrowserWindowOpener(resource);
opener.setFeatures("");
opener.extend(ui);
}
Now clicking the button the first time does not work. Clicking it the second time works. Clicking it the third time, opens two windows. This increases on every further click.
I also want to open the pdf using the context menu e.g.
table.addActionHandler(new Handler()...
There I don't even have a button to extend. I would prefer to, not use the .extend() part and just open a new window. How can I do that?
EDIT: This blocks the button from opening mulitple instances, still not a nice solution and the first click does not work.
Collection<Extension> extensions = ui.getExtensions();
for (Extension e : extensions) {
if (e instanceof BrowserWindowOpener) {
((BrowserWindowOpener) e).setResource(resource);
return;
}
}
I guess I would need to create a BrowserWindowOpener for every print Button in my Table.
Not a very clean solution, the table may contain lots of rows which would create a lot of BrowserWindowOpener instances which will never be used. The context menu problem would not be solved as well.
EDIT2: This is the other solution I tried:
ResourceReference rr = ResourceReference.create(resource, ui, "print");
Page.getCurrent().open(rr.getURL(), "blank_");
Here I get the following error:
Button (175) did not handle connector request for
print/2016_9090_R_1634500091131558445.pdf
You can use the FileDownloader to achieve what you want.
FileResource resource = new FileResource(pdfFile);
FileDownloader downloader = new FileDownloader(resource);
Button pdf= new Button("Download PDF");
downloader.extend(pdf);
Use this code
Window window = new Window();
((VerticalLayout) window.getContent()).setSizeFull();
window.setResizable(true);
window.setCaption("Exemplo PDF");
window.setWidth("800");
window.setHeight("600");
window.center();
StreamSource s = new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
try {
File f = new File("C:/themes/repy.pdf");
FileInputStream fis = new FileInputStream(f);
return fis;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, "repy.pdf", mainLayout.getApplication());
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.addComponent(e);
getMainWindow().addWindow(window);

dynamically adding hyperlinks to rtf file in JEditorPane

I am currently building a word processor for use in a multi-window media annotation tool, written in Java. It is for film students to write essays and embed them with links to multimedia clips.
I want the user to be able to highlight text in an rtf document and create a link to a media file in the project. When clicked the link will display the media in its associated window.
I would like to know if it is possible to dynamically create hyperlinks in rtf documents in Java? As is possible in Word, for example.
At the moment I am using a JEditorPane with the Advanced RTF Editor Kit (http://java-sl.com/advanced_rtf_editor_kit.html). I am struggling to find any sort of a solution.
Any help or pointers greatly appreciated.
Thanks
Edit:
code, with parts 1 & 3 from # Eric's answer added
`item3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
//use FX thread to open FileChooser
Platform.runLater(new Runnable() {
#Override
public void run() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("create link");
String startDirectory = System.getProperty("user.home") + File.separator + "Pictures";
fileChooser.setInitialDirectory(new File(startDirectory));
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JPEG files (*.jpg)", "*.jpg");
FileChooser.ExtensionFilter extFilter2 = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
FileChooser.ExtensionFilter extFilter3 = new FileChooser.ExtensionFilter("JPG files (*.jpeg)", "*.jpeg");
fileChooser.getExtensionFilters().addAll(extFilter,extFilter2, extFilter3);
File imageFile = fileChooser.showOpenDialog(stage);
if(imageFile != null){
Image image = ImageViewerController.getImage();
try {
image = new Image(imageFile.toURI().toURL().toExternalForm().toString());
int start = textArea.getSelectionStart();
int end = textArea.getSelectionEnd();
textArea.getDocument().remove(start, end);
String newString = "{\field{\*\fldinst HYPERLINK 'http://www.google.com/'}{\fldrslt http://www.google.com}}";
textArea.getDocument().insertString(start, newString , null);
textArea.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent hle) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
System.out.println(hle.getURL());
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(hle.getURL().toURI());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});`
I think there are various parts in your question:
1. Replace selected text in a Document:
Get the selected range with:
int start = editorpane.getSelectionStart();
int end = editorpane.getSelectionEnd();
Replace the text with:
editorpane.getDocument().remove(start,end);
editorpane.getDocument().insertString(start, newString, null);
Note: replace null with actual attribute set if needed.
2. Create a RTF-formatted hyperlink. I think this post has everything.
3. React to hyperlink clicks: As explained in the docs, you must add a HyperlinkListener to the editor pane to open the corresponding media. However a condition for this to work is that the editor kit generates HyperlinkEvents when hyperlinks are clicked. This is definitely the case for HTML documents, but since you are using a 3rd party library, I cannot confirm it will work the same way...

How to pass a file location as a parameter as a string?

Currently I pass a hardcoded string file location to my object method which uses the string in the .getResources() method to load an image file. I am now trying to chooses an image using a load button and pass the loaded file location as a string into the getResource() method. I am using the filename.getAbsolutePath() method to retrieve the file location then passing the filename variable into the object method however this provides me with the following error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
The line of code that it points to having the error is the .getResources line where the image is loaded. I will post the code below to better understand my problem.
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File loadImage = fc.getSelectedFile();
String filename = loadImage.getAbsolutePath();
filename = filename.replaceAll("\\\\", "\\\\\\\\");
picLocation = filename;
ImageSwing imageSwing = new ImageSwing(filename);
System.out.println(filename);
}
}
The output of the file name is correct yet it still wont pass into the object.
public class ImageSwing extends JFrame
{
public JLabel label;
public ImageSwing(String S){
super("Card Stunt"); //Window Title
setLayout(new FlowLayout()); //lookup grid layout
Icon flag = new ImageIcon(getClass().getResource(S));
label = new JLabel(flag);
label.setToolTipText(S);
setSize(1350, 800);
//setMinimumSize(new Dimension(1200, 760));
}//main
}
It seems like you create an absolute filename with loadImage.getAbsolutePath(), but then you try to use this as a class path resource with new ImageIcon(getClass().getResource(S)).
Instead, you should just pass the absolute filename, as a string, to ImageIcon:
Icon flag = new ImageIcon(S);
Also, don't forget to add the label to the frame...
getContentPane().add(label);
Also, I'm not on Windows right now, but I don't think filename.replaceAll("\\\\", "\\\\\\\\"); is necessary.

How to enforce that the iText PageEvent.onStartPage() is called before content is written to the document

Usually onStartPage() is called before any content is written.
In my use case its somehow invoked after some content is written to the new page.
What I do:
Create a Paragraph with some introduction
Create an Element with setKeepTogether(true). This element is so big, that iText will put it on the next page (what is the correct behaviour).
Now the onStartPage() is called after the element is added to the new page.
I depend on this method because i need to add a small text like continuation of xx to the top of the page.
This example reproduces the behaviour:
public class Main {
public static String someTompic = null;
public static void main(final String[] args) throws Exception {
final Document document = new Document(PageSize.A7);
final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("text.pdf"));
// This PageEventHelper should write a small text "Continuation: ..." at the beginning if
// a PageBreak was forced by "keepTogether"
writer.setPageEvent(new PdfPageEventHelper() {
#Override
public void onStartPage(final PdfWriter writer, final Document document) {
try {
if (someTompic != null)
document.add(new Paragraph("Continuation: " + someTompic));
}
catch (final DocumentException e) {
e.printStackTrace();
}
}
});
document.open();
// Now I add the introduction text
document.add(new Paragraph("A nice \nIntroduction \nover some lines."));
// Now I put my "huge" thing. If this breaks,
// the first line of the new page should be Continuation of ...
someTompic = "smth.";
final Paragraph paragraph = new Paragraph("What is \nthe answer \nto life the \nuniverse and \neverything?\n\nThe Answer to \nthis question \nis:\n42");
paragraph.setKeepTogether(true);
document.add(paragraph);
document.close();
}
}
This Link shows the broken PDF: PDF on Github

Uploading Files through GWT-RPC?

Uploading files with GWT is usually done with a FileUpload inside a FormPanel like this:
// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
form.setAction("/myFormHandler");
// Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
// Create a TextBox, giving it a name so that it will be submitted.
final TextBox tb = new TextBox();
tb.setName("textBoxFormElement");
panel.add(tb);
// Create a ListBox, giving it a name and some values to be associated with
// its options.
ListBox lb = new ListBox();
lb.setName("listBoxFormElement");
lb.addItem("foo", "fooValue");
lb.addItem("bar", "barValue");
lb.addItem("baz", "bazValue");
panel.add(lb);
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);
// Add a 'submit' button.
panel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
}));
Are there any other ways to handle file upload with GWT? Is it possible to do in with GWT-RPC or REST?
Edit: Browser requirement is Only Webkit
With modern browsers you can get the raw bytes of the input type=file (in a base64 data url). Having the bytes you can send them whatever the way you like.
Here's some code, displaying a file input dialog and getting the raw bytes (dataURL):
class Util {
static native void info (Object obj) /*-{
if ($wnd.console && $wnd.console.log) $wnd.console.log (obj)
}-*/;
/** Fires a "click" event on an HTML element. */
public static native void click (final JavaScriptObject element) /*-{
if (element.click) element.click();
}-*/;
/** Read a file from the local filesystem. The file should have been choosen via an `input type=file`.
* See also: http://www.html5rocks.com/ru/tutorials/file/dndfiles/; http://www.w3.org/TR/FileAPI/ */
public static native void readFile (JavaScriptObject inputFile, V1<String> andThen) /*-{
var files = inputFile.files
if ($wnd.console) $wnd.console.log ('readFile; input: ', inputFile, files)
if (!files || !files.length) return
var reader = new FileReader()
reader.onload = function (progressEvent) {
//$wnd.console.log ('read event: ', progressEvent, 'read: ', reader.result)
andThen.#client.Closure.V1::call(Ljava/lang/Object;)(reader.result)
}
reader.readAsDataURL (files[0])
}-*/;
}
// Remove old form.
final Element oldForm = Document.get().getElementById ("uploadForm");
if (oldForm != null) oldForm.getParentNode().removeChild (oldForm);
// A hidden form used to upload the files.
final FormPanel form = new FormPanel();
form.getElement().setId ("uploadForm");
final Style formStyle = form.getElement().getStyle();
formStyle.setDisplay (Display.INLINE_BLOCK); formStyle.setOverflow (Overflow.HIDDEN); formStyle.setWidth (0, Unit.PX); formStyle.setHeight (0, Unit.PX);
form.setAction ("http://.../");
form.setEncoding (FormPanel.ENCODING_MULTIPART); form.setMethod (FormPanel.METHOD_POST);
final FileUpload upload = new FileUpload(); upload.setName ("image");
form.add (upload);
RootPanel.get().add (form);
upload.addChangeHandler (new ChangeHandler() {public void onChange (final ChangeEvent event) {
Util.info ("Loading: " + upload.getFilename());
Util.readFile (upload.getElement(), new V1<String>() {public void call (final String dataURL) {
Util.info ("Loaded: " + upload.getFilename() + " (url is " + dataURL.length() + " bytes)");
}});
}});
// Trigger the upload dialogue. See also: http://aspalliance.com/articleViewer.aspx?aId=1441&pId=-1
Util.click (upload.getElement());

Categories

Resources