如何在scala.swing.Table中添加ComboBox作为单元格编辑器?

时间:2015-12-11 09:50:54

标签: swing scala jtable jcombobox scala-swing

我试图在Scala Swing应用程序的第二列中为每个单元格添加ComboBox作为列单元格编辑器,并且很难做到。以下代码显示了我到目前为止所尝试的内容,请帮助我更改代码以完成任务。

REFLECTABLE

更新

刚发现similair问题:How to embed a (working) Button in a Swing Table in Scala?会尝试建议的方法。

2 个答案:

答案 0 :(得分:1)

感谢Nickal提示。我自己的解决方案是原始代码的修改版本,仅在此处发布更改。

修改导入块:

import scala.swing._
import scala.swing.Swing._
import javax.swing._
import javax.swing.table.{TableCellEditor, AbstractTableModel}
import java.awt.{Component => AWTComponent}

添加了两个特性,可以在新类中混合使用java类:

//////////////////////////////////////////////////////////////////////////////////////////////////
trait AbstractCellEditorTrait extends AbstractCellEditor

//////////////////////////////////////////////////////////////////////////////////////////////////
trait TableCellEditorTrait extends TableCellEditor

//////////////////////////////////////////////////////////////////////////////////////////////////
class comboboxEditor(val currentValue: AnyRef) extends AbstractCellEditorTrait with TableCellEditorTrait {
  private val cb  = new ComboBox(Array("Value1", "Value2", "Value3"))
  cb.selection.item = currentValue.toString

  def getCellEditorValue: AnyRef = cb.selection.item.asInstanceOf[AnyRef]

  def getTableCellEditorComponent(tab: JTable, value: AnyRef, isSelected: Boolean, row: Int, col: Int): AWTComponent = {
    cb.peer.asInstanceOf[AWTComponent]
  }
}

修改后的代码在TestTable类中设置单元格编辑器(以val Col1 = peer.g开头的3行代码替换为下面的代码):

  override def editor(row: Int, col: Int): TableCellEditor = {
    if (col == 1) 
      new comboboxEditor(mymodel.getValueAt(row, col))
    else 
      super.editor(row, col)
    }

答案 1 :(得分:0)

基于 e_z 的代码,我为公共代码分离了一个BaseEditor抽象类,因为最终我还需要实现isCellEditable。在BaseEditor的子类中,您需要一个editor的实例,它是您的组件并实现getCellEditorValue

  abstract class BaseEditor extends AbstractCellEditor with TableCellEditor {
    protected val editor: Component  // scala.swing.Component

    override def isCellEditable(e: EventObject): Boolean= {
      if (super.isCellEditable(e)) {
        e match {
          case me: java.awt.event.MouseEvent => me.getClickCount >= 2
          case ke: java.awt.event.KeyEvent => 
            // F2 not working, for some reason keypress arrives as ActionEvent
            ke.getKeyCode == java.awt.event.KeyEvent.VK_F2  
          case ae: java.awt.event.ActionEvent => false // ignore for now
          case x => false  // otherwise ignore
        }
      } else false
    }

    def getTableCellEditorComponent(table: JTable, value: AnyRef,
                                    selected: Boolean, row: Int, col: Int): AWTComponent= {
      editor.peer.asInstanceOf[AWTComponent]
    }

  }

  // example extending BaseEditor and custom StringData object
  case class StringData(s: String)
  class TextFieldEditor(current: StringData) extends BaseEditor {
    protected val editor= new TextField(current.s)

    def getCellEditorValue: AnyRef= StringData(editor.text)
  }