Display Options for Text Descriptions - Java Swing - java

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.

Related

Clickable links from ArrayList in JOptionPane

I'm trying to implement a history-button in my Browser class (created in eclipse), and I want the links in the button to be clickable. Here is my code that gets initiated when the user presses the button History:
private void showMessage() {
try {
String message = new String();
message = history.toString();
JOptionPane.showMessageDialog(null, message);
} catch (NullPointerException e) {
System.out.println("Something is wrong with your historylist!");
}
}
In the code above, history is a list with all the webpages that has been previously visited.
I have tried using the method presented here:
clickable links in JOptionPane, and I got it to work. The problem is, this solution only lets me predefine URL:s, but I want my list history to be displayed, and the URLs in it to be clickable.
For example, if I have visited https://www.google.com and https://www.engadget.com, the list will look like this: history = [www.google.com, www.engadget.com], and both links should be separately clickable.
This is the function that should be called when someone presses the history-button. It uses a JEditorPane with a HyperlinkListener. The string html in the code below adds the needed html-coding so that the HyperlinkListener can read and visit the webpages.
public void historyAction() {
String html = new String();
for (String link : history) {
html = html + "" + link + "\n";
}
html = "<html><body" + html + "</body></html>";
JEditorPane ep = new JEditorPane("text/html", html);
ep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
loadURL(e.getURL().toString());
}
}
});
ep.setEditable(false);
JOptionPane.showMessageDialog(null, ep);
}

GIF from external resource in page is not animating in apache wicket web application

I am using external images in my webaplication, everything wass fine until I wanted to add animated gif there, the gif loads, but it doesn't animate.
Java code:
File sourceimage = new File("loading_img.gif");
try {
final BufferedDynamicImageResource r = new BufferedDynamicImageResource("GIF");
r.setImage(ImageIO.read(sourceimage));
add(new Image("gif", r));
} catch (Exception e) {
e.printStackTrace();
}
HTML:
<img wicket:id="gif"/>
EDIT:
Tried martin-g suggestion, gif still doesn't animate
try {
final BufferedDynamicImageResource r = new BufferedDynamicImageResource("GIF"){
#Override
protected void setResponseHeaders(AbstractResource.ResourceResponse data,
IResource.Attributes attributes){
super.setResponseHeaders(data, attributes);
data.setContentType("image/gif");
}
};
r.setImage(ImageIO.read(sourceimage));
add(new Image("gif", r));
} catch (Exception e) {
e.printStackTrace();
}
The problem is that the content type is not automatically set.
You will need to override org.apache.wicket.request.resource.AbstractResource#setResponseHeaders() and set with via resourceResponse.setContentType(String).
Maybe this should be done automatically by Wicket in org.apache.wicket.request.resource.DynamicImageResource, since it knows the format ("png", or "gif" as in your case). Please file a ticket in Wicket's JIRA for this improvement! Thanks!

Showing correctly a website on JEditorPane 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.

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

FileNotFoundException error while running java program

I am getting a FileNotFoundException while running code.
my filname is filecontent.java...
Definition: I want to create a program having 4 TextFields and 4 TextAreas. If one types the name of the file in TextField, then its content should be shown in corresponding TextArea.
Error :
Exception e : java.io.FileNotFoundException :
My Code :
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class filecontent extends Frame implements ActionListener
{
TextField t[]=new TextField[4];
TextArea ta[]=new TextArea[4];
Button submit,exit=new Button("Exit");
Panel p1;
filecontent()
{
setGUI();
setRegister();
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e : "+ioe);
}
setTitle("FileData");
setVisible(true);
setSize(300,300);
setLocation(500,200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent we)
{ System.exit(0); }
});
}
void setGUI()
{
p1=new Panel();
p1.setLayout(new GridLayout(5,4,10,10));
for(int i=0;i<4;i++)
{
t[i]=new TextField(10);
ta[i]=new TextArea();
p1.add(t[i]);
p1.add(ta[i]);
}
submit=new Button("Submit");
p1.add(submit);
p1.add(exit);
}
void setRegister()
{
submit.addActionListener(this);
exit.addActionListener(this);
}
void showfile() throws java.io.IOException
{
FileReader fin[]=new FileReader[4];
FileReader fn=new FileReader("filecontent.java");
BufferedReader br[]=new BufferedReader[4];
for(int i=0;i<4;i++)
{
fin[i]=new FileReader(t[i].getText());
}
int cnt=1;
String s;
fn=fin[0];
br[0]=new BufferedReader(fn);
while(cnt<=4)
{
if((s=br[cnt-1].readLine())!=null)
{
ta[cnt-1].append(s+"");
}
else
{
fin[cnt-1].close();
cnt++;
fn=fin[cnt-1];
br[cnt-1]=new BufferedReader(fn);
ta[cnt-1].setText("");
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e"+ioe);
}
}
else if(ae.getSource()==exit)
{
System.exit(0);
}
}
public static void main(String ar[])
{
new filecontent();
}
}
You don't have a NullPointerException. You have a FileNotFoundException. As the name of this exceptions says this is because a file you try to open isn't found.
The first file access that fails is this one:
FileReader fn=new FileReader("filecontent.java");
If your java file is located within a src (or any other) folder of your project you have to add the folder. E.g. src/filecontent.java
Some other notes:
By convention java class names start with upper case letters
Your variable names t, ta, p1, etc. can be confusing. Why not use textFields, textAreas, panel?
I think you will run into an ArrayIndexOutOfBoundsException in this line while(cnt<=4)
. Array indices start with 0 and end with n - 1 (=3 in your case)
It can help debuging to print out the stacktrace in your catch block: ioe.printStackTrace(). This gives you the exact line number where your code fails
Your exception may have come from this line
FileReader fn=new FileReader("filecontent.java");
I think you should use a full path, not just a file name.
First of all, why don't you use FileDialog instead of textField for the file. Secondly, you are using relative path so for your program to work, the file filecontent.java must be in the same place as your .class file
When reading a file in java the syntax for filepath varies system to system. So you should apply the path according to the operating system you are using.
Also for your code the file filecontent.java should be in the same directory.
Based on your comments, the answer is that the file appears as a.txt in explorer but is actually a.txt.txt Showing file extensions in explorer avoids this issue/confusion.
When you use a file path it is relative to the working directory, i.e. where the application was run. Not where the source code can be found. If you don't know what your working directory is, you should use a full path name.

Categories