Museless
Museless

Reputation: 137

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

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 contain the info for each entry in the table. When trying to put this into a Table, ho=w do I go about assigning the Column headers?

Syntax suggestions would be greatly appreciated.

Pseudocode:

Data=ArrayBuffer()
Data(0)={"Name","Birthday","ID"}
Data(1)={"Bob", "07/19/1986", "2354"}
Data(2)={"Sue", "05/07/1980", "2355"}
Data(3)={"Joe", "08/12/1992", "2356"}
Data(4)={"Jim", "11/20/1983", "2357"}

I want to put this into a Table where Data(0) describes the column headers, and the subsequent rows describe rows in the table, but I can't figure out how to set the row headers.

Upvotes: 4

Views: 1166

Answers (2)

Luigi Plinge
Luigi Plinge

Reputation: 51109

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.

Upvotes: 3

aishwarya
aishwarya

Reputation: 1986

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.

Upvotes: 0

Related Questions