How do I configure the Column names in a Scala Table?

后端 未结 2 2039
滥情空心
滥情空心 2020-12-19 17:09

I am writing a Scala program to manage a database, and have drawn all of the data into a 2-dimensional ArrayBuffer where row 0 is the column names, and the subsequent rows c

相关标签:
2条回答
  • 2020-12-19 17:28

    assuming you are talking of swing, if you put your table inside a scrollpane and create your table model based on the array buffer shown, the first row will be taken as column names by default.

    0 讨论(0)
  • 2020-12-19 17:34

    The easiest way to put data in a Table is to use its constructor:

    new Table (rowData: Array[Array[Any]], columnNames: Seq[_]) 
    

    The slightly tricky thing here is that arrays are not covariant (see Why doesn't the example compile, aka how does (co-, contra-, and in-) variance work?), which means that an Array[String] is not a subtype of Array[Any]. So you need some way of turning one into the other: a map does the job.

    Also, for the column names to show, you need to put the table in a ScrollPane.

    import swing._
    import collection.mutable.ArrayBuffer
    
    object Demo extends SimpleSwingApplication {
    
      val data = ArrayBuffer(
        Array("Name","Birthday","ID"),
        Array("Bob", "07/19/1986", "2354"),
        Array("Sue", "05/07/1980", "2355")
      )
    
      def top = new MainFrame {
        contents = new ScrollPane {
          contents = new Table(
            data.tail.toArray map (_.toArray[Any]),
            data.head
          )
        }
      }
    }
    

    Will give you a table:

    table

    Edit: you can also use a cast: data.tail.toArray.asInstanceOf[Array[Array[Any]]], which is more efficient than mapping.

    0 讨论(0)
提交回复
热议问题