我对 Scala 与 Swing JTree组件(Java)之间的互操作性存在问题。
JTree没有正确更新,除非我停止显示JOptionPane以提示用户输入新实体的名称。该行标有[* * *]。如您所见,我提供了静态文本“xxx”,注释掉了对JOptionPane方法的调用。在这种情况下,JTree按预期正确更新。
我认为它可能与Swing线程模型有关,但是将更新文本包装在Runnable类中并不能解决问题。另请参阅Why isn't my JTree updating when the TreeModel adds new nodes?
为什么JOptionPane会阻止JTree正确更新节点?
我这样做是因为Scala还没有允许动态更新的Swing Tree实现。见http://github.com/kenbot/ScalaSwingTreeWrapper
任何提示或指示都将不胜感激。
干杯,
佰
import scala.swing._
import javax.swing.{JOptionPane,JTree,SwingUtilities}
import javax.swing.tree.{DefaultTreeModel,DefaultMutableTreeNode,TreePath}
object XApp extends SimpleSwingApplication {
val APP_NAME: String = "AppName"
def getNameDialog(q: String): String =
{
JOptionPane.showInputDialog(top.self, q, APP_NAME, JOptionPane.PLAIN_MESSAGE);
}
def menuProjectNewX = {
// Get the name of the X
var name = "xxx"; // getNameDialog ("Enter the name of the X:") [***]
def doUpdate = new Runnable() {
def run()
{
pl ("Running");
// Get the root
var root = treeModel.getRoot().asInstanceOf[DefaultMutableTreeNode]
// Insert new object
var newNode = new DefaultMutableTreeNode(name)
treeModel.insertNodeInto(newNode, root, root.getChildCount())
// Expand the tree
var tp = new TreePath(newNode.getPath().asInstanceOf[Array[Object]])
tree.scrollPathToVisible(tp)
}
}
SwingUtilities.invokeLater(doUpdate);
}
var tree: JTree = null
var treeModel: DefaultTreeModel = null
var flow: FlowPanel = null
def top = new MainFrame {
// Create the menu bar
menuBar = new MenuBar() {
contents += new Menu("Project") {
contents += new MenuItem(Action("New X...") { menuProjectNewX })
}
}
title = APP_NAME
preferredSize = new Dimension (1000, 800)
location = new Point(50,50)
treeModel = new DefaultTreeModel(new DefaultMutableTreeNode("(root)"))
tree = new JTree(treeModel)
//flow = new FlowPanel
var splitPane = new SplitPane (Orientation.Vertical, new Component {
override lazy val peer = tree
}, new FlowPanel)
splitPane.dividerLocation = 250
contents = splitPane
}
}
答案 0 :(得分:1)
问题在于,每次显示JOptionPane
时,您都会创建一个新的Frame,而不是重用MainFrame。请注意,top
是一种方法,当您引用“顶部”以显示JOptionPane
时,您正在创建new MainFrame
。因此,最后,您将节点添加到MainFrame中与正在显示的树不同的树。
解决此问题的一种方法是简单地将MainFrame存储在变量中:
var mainFrame: MainFrame = null
def top =
{
mainFrame = new MainFrame {
// Rest of the code
}
mainFrame
}
}
// To show the JOptionPane
JOptionPane.showInputDialog(mainFrame.self, q, APP_NAME, JOptionPane.PLAIN_MESSAGE);