Search code examples
javastringswingreferencecall

Java: passing the value of a String to another class to use for setText on Pane


I am quite new to this, I do not understand how classes communicate properly despite reading the docs, I think I need a working example to drill it in.

I have a Jlist and a JEditorPane sharing a JSplitPane. the list functionality is fine, however my Jeditorpane is in another class, I have obtained the string I need by:

public void setBookmarkPreview(ListSelectionEvent evt) {
bookmarkString = (String)this.getSelectedValue();
//System.out.println(bookmarkString);

this all works, however I have no idea how to pass this string to my "BookmarkPreview" class which extends JEditorPane, just so I can display the retrieved result above on the editor pane from the second class.

I've tried reading online but I can't get my head around the context.

I created

public static String bookmarkString;

Thinking it would be updated based on my list listener method, but the result in class 2 prints "null" so I am clearly missing something here.

Here is the second class where I tried to call the public static string

public class BookmarkPreview extends JEditorPane {

public BookmarkPreview() {

BookmarkPane test = new BookmarkPane();

this.setEditable(false);
setText(BookmarkPane.bookmarkString);
System.out.println(BookmarkPane.bookmarkString);
}   
}

Please, if you can provide an example using my wording it would be greatly appreciated, directing me to the docs won't help I assure you have have been trying for ages to wrap my head around it from scratch.

*UPDATE**

ok I have created getters/setters:

public void bookmarkPreview(ListSelectionEvent evt) {
bookmarkString = (String)this.getSelectedValue();
setBookmarkString(bookmarkString);
 }


public String getBookmarkString() {
    return bookmarkString;
}

public void setBookmarkString(String bookmarkString) {
    this.bookmarkString = bookmarkString;
}

and updated the class that wants to recieve it:

public BookmarkPreview() {
BookmarkPane test = new BookmarkPane();
test.getBookmarkString();
this.setEditable(false);
setText(test.getBookmarkString());
System.out.println(test.getBookmarkString());
}   
}   

Still nothing appears in the JEditorPane.


Solution

  • This will depend on which way you want the communication to work.

    To my mind, the editor doesn't care about the book mark list, but the list will want to know about the editor (so it can set the book mark).

    What I would do is maintain a reference to the editor within the list component (passed in either via the constructor or a setter of some kind) which would allow the list, when it's changed to call a method of the editor that would update the bookmark position (such as setBookMark).

    Equally, I would allow the list to request a book mark from the editor at it's current position, maybe something like newBookMark or such