Showing correctly a website on JEditorPane java - java

I returned my JEditorPane in my program to a website, like google example,
but it doesn't show correctly the page, well without its css style.
uh,
check my code :
JEditorPane editorPane = new JEditorPane() {
public boolean getScrollableTracksViewportWidth() {
return true;
}};
editorPane.setEditable(false);
HTMLEditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
editorPane.setDocument(doc);
editorPane.setEditorKit(kit);
try {
editorPane.setContentType("text/html");
editorPane.setPage("http://www.google.fr/");
}catch (IOException e) {
editorPane.setContentType("text/html");
editorPane.setText("<html>We can't load this page</html>"
+ e.getMessage() + " ");
}
editorPane.setBounds(295, 265, 491, 474);
editorPane.setBorder(new LineBorder(new Color(0, 0, 0)));
pan.add(editorPane);
I just want to show a website in a java component to show news and others information,
can anyone help me please?

A JEditorPane only supports basic HTML.
For full support you can use the default browser of your system. Check out the section from the Swing tutorial on How to Integrate with the Desktop Class for a working example that uses the "BROWSE" functionality.

Related

I want to build a PDF doc, using Glen K. Peterson's Pdf Layout Manager, but I'm stuck at building a table

I've decided to use Glen K Peterson's Pdf Layout Manager available on GitHub(https://github.com/GlenKPeterson/PdfLayoutManager) to generate PDF documents with my app, I've imported the source files and the pom.xml dependencies and everything, it's working just fine.
The problem is, I'm trying to build a table in one of the documents I want to generate with a button click. I have no idea how to extract(use) the TableBuilder, as I'm getting the error message inside my JDeveloper IDE, that the class has private access.
Here's my code:
private void jBtnSalvareVerMetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnSalvareVerMetActionPerformed
// TODO add your handling code here:
PDDocument document = new PDDocument();
try {
PDPage page = new PDPage();
document.addPage(page);
PDFont font = PDType1Font.COURIER;
PDPageContentStream contents = new PDPageContentStream(document, page);
contents.beginText();
contents.setFont(font, 14);
contents.newLineAtOffset(50, 500);
Coord coordinate = new Coord(10, 700);
PdfLayoutMgr pageMgr = PdfLayoutMgr.newRgbPageMgr();
LogicalPage locatieTabel = pageMgr.logicalPageStart();
TableBuilder tabel = new TableBuilder(locatieTabel, coordinate); // Getting the error at this point
contents.newLineAtOffset(10, 700);
contents.showText(tabel.toString());
contents.endText();
contents.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(MeniuTaburi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} finally {
try {
document.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(MeniuTaburi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
jLabelAverstismenteVerMet.setText("<html><center>Datele au fost salvate cu succes!</center></html>");
}//GEN-LAST:event_jBtnSalvareVerMetActionPerformed
I thought of changing the type of access permission from private to public, for the TableBuilder, but I don't think, that's the way it's actually supposed to work...
Is there any other way, I can build the table I need, without resorting to changing the access modifier, inside the TableBuilder class??
You try to use
TableBuilder tabel = new TableBuilder(locatieTabel, coordinate); // Getting the error at this point
But that constructor is private
private TableBuilder(LogicalPage lp, Coord tl) {
logicalPage = lp; topLeft = tl;
}
I.e. you are not meant to use it. Unfortunately there also is no JavaDoc indicating what you should use instead. But looking at the TableBuilder source a bit beyond that constructor, you'll find immediately following this:
public static TableBuilder of(LogicalPage lp, Coord tl) {
return new TableBuilder(lp, tl);
}
Thus, instead of your direct constructor call you should use this factory method:
TableBuilder tabel = TableBuilder.of(locatieTabel, coordinate);

Display Options for Text Descriptions - Java Swing

Okay, I have this program I am writing and would love some oversight please.
This program of sorts, uses a JList and JListSelectionListener to output a number of images onto, 1/2 vertically-split JPanes. Of these JPanes, as mentioned beforehand; one displays the images and in the bottom JPanel, a JEditorPane reads text. For the JEditorPane, I have an HTML doc. styled and being read from. This in theory, is my description of each image. Except, I cannot redirect the JEditorPane as too, read from aforementioned HTML files whose URLs or paths are accessed via a String Array[].
Main Points/Questions (tldr;)
How do I have this JEditorPane read from a different HTML file each time a new image is selected from the JList?
Should I be using a JTextPane or something else instead? Only, too my knowledge, styling might be in-or-out of the question. So, what am I doing wrong or differently and should be?
Code
private String[] fileName = { "htmlDoc1", "htmlDoc2", "htmlDoc3", "htmlDoc4" };
protected JScrollPane createEditorList() {
JEditorPane editorPane = createEditorPane(fileName[list.getSelectedIndex()]);
JScrollPane editorScrollPane = new JScrollPane(editorPane);
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
editorScrollPane.setPreferredSize(new Dimension(250, 145));
editorScrollPane.setMinimumSize(new Dimension(10, 10));
return editorScrollPane;
}
private JEditorPane createEditorPane(String file) {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
java.net.URL helpURL = Bobbleheads.class.getResource("/images/bobbleheads/" + file + ".html");
if (helpURL != null) {
try {
editorPane.setPage(helpURL);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + helpURL);
}
} else {
System.err.println("Couldn't find file: " + fileName);
}
return editorPane;
}
public void valueChanged(ListSelectionEvent e) {
JList<?> list = (JList<?>) e.getSource();
updateLabel(imageNames[list.getSelectedIndex()]);
createEditorPane(fileName[list.getSelectedIndex()]);
}
Thank you too everyone, contributing any way possible!
Crunching in a few methods solved this Java singleton. With the outstanding help from AJNeufeld, Andrew Thompson & Stack Overflow of course!
Heres how:
Original methods for change:
protected JScrollPane createEditorList() {
private JEditorPane createEditorPane(String file) {
and the public void valueChanged(ListSelectionEvent e) { method were replaced with and replicated into these newer code blocks.
Code:
New, rescripted methods:
protected JScrollPane makeAEditorPane() {
JScrollPane editorScrollPane = new JScrollPane(makeAEditorList());
editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
editorScrollPane.setPreferredSize(new Dimension(250, 145));
editorScrollPane.setMinimumSize(new Dimension(10, 10));
return editorScrollPane;
}
protected JEditorPane makeAEditorList() {
editorPane = new JEditorPane();
editorPane.setEditable(false);
return editorPane;
}
private void feedEditor(String name) {
URL helpURL = Bobbleheads.class.getResource("/images/bobbleheads/" + name + ".html");
if (helpURL != null) {
try {
editorPane.setPage(helpURL);
} catch (IOException e) {
System.err.println("Attempted to read a bad URL: " + helpURL);
}
} else {
System.err.println("Couldn't find file: TextSampleDemoHelp.html");
}
}
public void valueChanged(ListSelectionEvent e) {
JList<?> list = (JList<?>) e.getSource();
updateLabel(imageNames[list.getSelectedIndex()]);
feedEditor(htmlDocs[list.getSelectedIndex()]);
}
Understanding what has changed:
Of the two original methods, three new methods were deduced. createEditorList() & createEditorPane(String file) became makeAEditorPane(), makeAEditorList() & feedEditor(String name). Simply by splitting up the components editorScrollPane & editorPane during formation thanks to, #AJNeufeld.
Very next, the new method feedEditor(String name), did exactly what its name implies. Feeds the initiation of our URL here, allocating a HTML file for the editorPane to derive and load thanks to, #Andrew Thompson.
Accessing the method: feedEditor(htmlDocs[list.getSelectedIndex()]);, inside of the valueChanged(ListSelectionEvent e) method, paved the way for an event to occur. An event between a JList known as list.
Wrapping things up...
Now, the event brought a change in the URL discussed on earlier. Here, it is relatively simply put; allowing for switching between JList selections, activates HTML files located as project resources.
That's it! Thank you everybody and stay safe.

Why do we not get the same display of a particular font in web browser and java swing

Suppose a font Kalpurush.ttf (you may find this font here). As it is an Assamese Font and may not have installed in everyone's computer, so, I've embedded this font in my website. It displays fine in any browser, (except android webview. I do not have any headache about android). In fact I've never found any Assamese font to be so nice.
Now I've tried this same font in a Java Swing Application. I've written this class:
public class AssameseFont {
public AssameseFont(){}
public Font Assamese(){
File file = new File("kalpurush.ttf");
Font as = null;
try{
FileInputStream input = new FileInputStream(file);
as = Font.createFont(Font.TRUETYPE_FONT, file);
as = as.deriveFont(Font.PLAIN, 18);
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(as);
}
catch(FontFormatException | IOException e){
JOptionPane.showMessageDialog(null, ""+e);
}
return as;
}
}
I use to call this in my components using setFont() method.
But some of my texts does not display as it should be.
Why does it happen? Is it a font problem? Or am I doing anything wrong in my java code?
As it is an Assamese Font and may not have installed in everyone's computer, so, I've embedded this font in my website. ..
File file = new File("kalpurush.ttf");
That file will point to a (non-existent) file on the user's machine.
The font must instead be accessed by URL.
See also Setting custom font.
The code seen on the linked thread, but with the kalpurush.ttf font.
import java.awt.*;
import javax.swing.*;
import java.net.URL;
class DisplayFont {
public static void main(String[] args) throws Exception {
URL fontUrl = new URL("http://assameseonline.com/css/kalpurush.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
font = font.deriveFont(Font.PLAIN,20);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
JLabel l = new JLabel(
"The quick brown fox jumps over the lazy dog. 0123456789");
l.setFont(font);
JOptionPane.showMessageDialog(null, l);
}
}

clickable email address as a JLabel in java

For the "About" dialog of my application,
I have a JLabel which I have defined using html tag as follows:
JLabel myEmail = new JLabel(
"<html><br><font size=2><a href=mailto:abc.pqr#xyz.com>abc.pqr#xyz.com</a>" +
"</font></html>");`
I want that on clicking this JLabel, the default email client (say Outlook) gets opened with the To field populated as abc.pqr#xyz.com and subject as a predefined text (say, Hi!).
How to do that?
Here is a snippet on how you could do this:
String address = "abc.pqr#xyz.com"; // global
JLabel label = new JLabel("<html><br><font size=2><a href=#>" + address + "</a></font></html>");
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().mail(new URI("mailto:" + address + "?subject=Hello"));
} catch (URISyntaxException | IOException ex) {
// ...
}
}
});
For demonstration purposes, the address variable is global here but you should use a concrete MouseAdapter subclass to pass in the associated email address. Best to steer clear of attempting to parse the HTML.
Unfortunately, HTML links within a JLabel are not "clickable" by default. Please, see this topic: How to add hyperlink in JLabel. It contains everything you may need to know about this topic.
Or if you do not mind using an extra library, you can consider using the JXHyperLink from the SwingX project

showDocument() does not display new window in IE8 with Java 7/Java 6u27

I have a Java Applet that interacts with the Java Plugin to show a document (just a URL) in a named browser window:
public class TestApplet extends Applet {
#Override
public void init() {
super.init();
final JButton showButton = new JButton("Show Google!");
showButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
getAppletContext().showDocument(new URL("http://google.com"), "Some Window Title");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
}
});
add(showButton);
}
}
This has worked historically but starting with Java 7 and Java 6u27, the window fails to open in Internet Explorer (tested in IE 8). If I use _blank as the window title (target) instead of Google, the window opens correctly (albeit in a new window each time).
I've tracked down this bug that was fixed for 6u27:
Vista/IE7 further showDocument focus issue with named targeted windows
Has anybody else experienced the same behaviour? Have you found a workaround (other than using "_blank")?
Edit
Updated the example. I wasn't actually using "Google" as the target, I was using "Some Window Title" (sorry!). It seems like this problem is unique to targets with spaces in the name.
It seems like this problem is unique to targets with spaces in the name.
Two possible solutions:
Replace the " " with "%20"
Don't use a space in the name of the target! (Though I thought that would be a 'no brainer'.)
Try this code, it should work.
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(info));

Categories