我对swing和scala都很陌生,但是我想在scala.swing.Table中单击一列时捕获,我一直无法弄清楚如何执行此操作。可以在scala中完成吗?我仍在学习如何阅读scala API,因此任何见解都会有所帮助,
答案 0 :(得分:1)
看起来Scala Swing还不支持表头事件,因此您可能需要执行以下操作,将鼠标侦听器直接添加到 JTableHeader 。
我确信有一种优雅的方法可以创建一个 scala.swing.Publisher 来将监听器与 listenTo 和反应集成在一起机制,这取决于是否值得额外的努力。
import java.awt.Dimension
import java.awt.event.{MouseEvent, MouseAdapter}
import swing._
import event.TableColumnsSelected
object TableQuestion extends SimpleSwingApplication {
val headers = Array.tabulate(10){"Col-"+_}.toSeq
val rowData = Array.tabulate[Any](10, 10){""+_+":"+_}
lazy val ui = new BoxPanel(Orientation.Vertical) {
val table = new Table(rowData, headers)
val label = new Label("")
val header = table.peer.getTableHeader()
header.addMouseListener(new MouseAdapter() {
override def mouseClicked(e: MouseEvent) {
val col = header.columnAtPoint(e.getPoint())
label.text = "Column header "+col+" selected"
}
})
listenTo(table.selection)
reactions += {
case TableColumnsSelected(_, r, _) =>
label.text = "Column "+table.selection.columns.leadIndex+" selected, range = "+r
}
contents += new ScrollPane(table)
contents += label
}
def top = new MainFrame {
title = "Table Column Selection"
preferredSize = new Dimension(400, 260)
contents = ui
}
}
此外,我发现TableColumnSelected事件提供的范围信息相当奇怪,它包含从当前点击到另一列中的上一次点击的连续列索引。也许我错过了一些原因。
答案 1 :(得分:1)
我能够以Don Mackenzie为例,使用Publisher和Reactor生成一些东西。
import java.awt.event.{MouseEvent, MouseAdapter}
import javax.swing.UIManager
import swing._
import event.TableEvent
object TableQuestion extends SimpleSwingApplication
{
val headers = Array.tabulate(10) {"Col-" + _}.toSeq
val rowData = Array.tabulate[Any](10, 10) {"" + _ + ":" + _}
lazy val ui = new BoxPanel(Orientation.Vertical) {
val table = new Table(rowData, headers)
val label = new Label("")
val header = table.peer.getTableHeader()
header.addMouseListener(new MouseAdapter() {
override def mouseClicked(e: MouseEvent) {
publish(ColumnHeaderClicked(table, header.columnAtPoint(e.getPoint())))
}
})
listenTo(table)
reactions += {
case ColumnHeaderClicked(_, column) => label.text = "Column header " + column + " selected"
}
contents += new ScrollPane(table)
contents += label
}
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName);
def top = new MainFrame {
title = "Table Column Selection"
preferredSize = new Dimension(400, 260)
contents = ui
}
}
case class ColumnHeaderClicked(override val source: Table, column: Int) extends TableEvent(source)
答案 2 :(得分:0)
请不要编写自己的表排序实现 - 请改用GlazedLists。你会感谢我的。您可能需要使用标准的JTable而不是swing.Table,但它可以处理您将要做的所有排序和过滤。