When casting to JBCefBrowser, a casting exception is returned
I have a tool window which contains only one content. As of now, the content is a JBCefBrowser. The code I am using to set the content of the tool window is the following:
class TaskDescriptionPanel(private val project: Project) : SimpleToolWindowPanel(true, true), Disposable {
var jbCefBrowser = JBCefBrowser(WELCOME_URL)
init {
initBrowser()
}
private fun initBrowser(){
val divPanel = JPanel(BorderLayout())
divPanel.border = IdeBorderFactory.createBorder(UIUtil.getBoundsColor(), SideBorder.ALL)
divPanel.add(jbCefBrowser.component, BorderLayout.CENTER)
setContent(divPanel)
}
...
Up to there all is working fine; the browser appears and works as expected.
Now, I want to implement a feature so that, depending on the file the user opens in the editor, I programmatically load a new URL to the browser.
The strategy I want to take in order to implement that feature is to access the content of the Tool Windows and then look for the JBCeFBrowser component and once I have that component, I can call the loadUrl() method to load the new URL.
Here is the code that tries to accomplish that strategy:
// Get the tool window
val myToolWindow = ToolWindowManager.getInstance(project).getToolWindow(ID)
// Access the (only) content in the tool window
val content = myToolWindow.contentManager.contents.first()
// Access the panel
val panel: JPanel = content?.component as JPanel
// Access the JBCefBrowser <-- Not working ok
val browser: JBCefBrowser = panel.components?.first() as JBCefBrowser
After executing the last line above, I get the following error:
java.lang.ClassCastException : com.intellij.ui.jcef.JBCefBrowser$3 cannot be cast to com.intellij.ui.jcef.JBCefBrowser
I do not understand what com.intellij.ui.jcef.JBCefBrowser$3 is. If use a JTextField or JButton, instead of a JBCefBrowser, I can execute the code above (with the appropriate casting) and I can access the properties of such component.
As mentioned before, my end goal is to programmatically load a new URL into the JBCefBrowser based on user behavior. I am trying to achieve that by accessing the content of the tool window and doing a casting to find the browser and then access its properties. However, that method is not working.
I would appreciate some assistance by either helping me do the appropriate casting so that I get access of the browser component or indicate a different direction to accomplish my goal.
Thank you in advance
请先登录再写评论。
Huberto,
In the initBrowser method, you're adding the JBCefBrowser's UI component to your tool window, so later – when accessing the TW components with:
you'll also get just its component, not the whole JBCefBrowser instance. That's why your code fails on the casting of the component-type object to the browser class.
To access share the state between the tool window and other parts of your plugin, you could use a project service.