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);
}
Related
I am working on a project right now where I use jsoup in a class with the function retrieveMedia in order to return an ArrayList filled with data from the webpage. I run it in a thread since you shouldn't be connecting to URLs from the main thread. I run it and join it. However, it doesn't work (I tested the same code in Eclipse separate from Android Studio and it worked fine). It seems that no matter what I do I can't get jsoup to connect to the webpage. Below is my class MediaRetriever.
public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}
Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mediaOutput;
}
}
Running this class's method from another class and it doesn't ever connect. Any ideas?
Since you say that the problem persists only in Android, it looks like that you should add the user agent string to your request - first get the user agent string of a browser that displays correctly the site, and then add it to the request:
doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();
And as a sidenote - if you are catching exception, don't print your own error message - print the original message, it may be very useful.
I have this JavaFx app when I press one of the buttons, an other javafx class lauch!
so all what i need to know is : when I press the back button of the seconde class I need to find the first window with the same values entred in the bigging !
here what I can do for now:
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
new MainApp().start(stage);
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
log.error(errors.toString());
}
}
});
I had the same problem and here is the solution:
let's suppose you have those 2 TextField one of them called apiurl and other called mainUrl ! all what you have to do is to to create String url = ""; and go to your button action and add this line : url=apiurl.getText(); in the initialize method in your controller add this : apiurl.setText(url); and this worked well for me !
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.
I am writing a selenium test where I am checking UI and functionlity of website.In functionlity I am entering username and passoword in input block and want to click on sign in button.All thing is working fine except sign in button.The click is also happening but it will not redirect on right page. It always redirects on
http://vma-dev.saas.trilogy.com/favicon.ico"
where
http://vma-dev.saas.trilogy.com is my base url. I am using following code..
For login using following function..
public void getLogin() throws InterruptedException
{
enterTextValueByElementNameInWindow(getBaseElement(),AppConstants.Html_Id_Common_Text_User ,AppConstants.USER_VAL);
//getBaseElement().keyUp(AppConstants.Html_Id_Common_Text_User,"m");
enterTextValueByElementNameInWindow(getBaseElement(),AppConstants.Html_Id_Common_Text_PWD ,AppConstants.PASSWORD_VAL);
//getBaseElement().keyUp(AppConstants.Html_Id_Common_Text_PWD,"3");
clickByElementInWindow(getBaseElement(), AppConstants.Html_Id_Common_Btn_Text_SignIn, true);
try
{
getBaseElement().wait(10000);
}
catch(IllegalMonitorStateException ie)
{
}
}
and for click on signIn button I am using following function..
public static void clickByElementInWindow(LoggingSelenium appWindow, String element, boolean waitForPageLoad)
{
LoggingAssert.assertTrue("Button Element " + element + " cannot be located",appWindow.isElementPresent(element), appWindow);
LoggingAssert.assertTrue("Button Element " + element + " is not visible",appWindow.isVisible(element), appWindow);
appWindow.click(element);
appWindow.setSpeed("500");
if (waitForPageLoad){
// wait for page to be ready
// appWindow.waitForPageToLoad(Integer.toString(AppConstants.APP_READY_TIME));
// sometimes page doesn't get loaded even with waitForPageToLoad. Use sleep to be safe.
try
{
Thread.sleep(AppConstants.APP_PAGE_LOAD_WAIT_TIME);
}
catch(InterruptedException ie)
{
// do nothing
}
}
}
I am badly stucked here.Any help is appriciated.
I am developing in J2ME, I need to show a text, and then an underlined link / button that people can press.
I cannot use Canvas.
As a temporal solution, I am using the typical command button but I would like to show this option on screen.
(I don't want to use any framework that implies to change everything so that it has a particular look, only an underlined link)
I found it, uff!!!
Command prospectoCommand = new Command("Prospecto", Command.EXIT, 1);
StringItem messageItem2 = new StringItem("", "", Item.HYPERLINK);
messageItem2.setText("push to go to the URL");
ItemCommandListener listener = new ItemCommandListener() {
public void commandAction(Command cmnd, Item item) {
if(cmnd==prospectoCommand)
{
try {
midlet.platformRequest(URL);
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
}
}
};
messageItem2.setDefaultCommand(prospectoCommand);