TableView
完成一个可重用的 View,用于列表打印
标题管理
API 样例
希望使用这套 API 达到下面的效果
1 2 3 4 5 6 7 <public void run() { TableView tableView = new TableView(); tableView.addTitle("id"); tableView.addTitle("Catgeory"); tableView.addTitle("Name"); tableView.display();}| id | Category | Name
List<String> titles
private property
表格标题
void addTitle(String item)
public method
为 tableView 增加一个标题
void display()
public method
按样例的格式打印标题
数据管理
API 样例
希望使用这套 API 达到下面的效果
1 2 3 4 5 6+7+8+9+10+11+12 13 < < <public void run() { TableView tableView = new TableView(); tableView.addTitle("id"); tableView.addTitle("Catgeory"); tableView.addTitle("Name"); for (int row = 0; row < 2; row++) { tableView.addRow(); for (int col = 0; col < 3; col++) { tableView.addItem(row + "." + col); } } tableView.display();}| id | Category | Name | 0.0 | 0.1 | 0.2| 1.0 | 1.1 | 1.2
LinkedList<LinkedList<String>> data
private property
二维 LinkedList,存储表格中的数据
提示
初始化时,可以写
1 data = new LinkedList<LinkedList<String>>();
void addRow()
public method
为 tableView 增加一行
提示
1 2 3 public void addRow() { data.add(new LinkedList<String>());}
void addItem(String item)
public method
在当前 tableView 的最下方的那一行,的右侧 追加一条数据,存储到 data 里
注意
我们假设用户在调用这个函数时,会保证一定让每行 item 的个数 和 title 的个数 一致
void display()
public method
更改现有代码,结合数据打印出固定格式的样子
打印时,需要对每一列的宽度进行预判,宽度应该是 这一列标题,和所有行这一列的数据最宽的宽度
< < <| id | Category | Name | 0.0 | 0.1 | 0.2| 1.0 | 1.1 | 1.2
提示 1
字符串 格式化显示
Formatting Print Output
提示 2
1 2 3 4 5 6 7 8 9 10 11 12 13 int width = 0;for (...) { ... width = ...;}String format = "%-" + witdh + "d"...for (...) { ... String cell = String.format(format, data.get(...).get(...)); Console.print("| "); Console.print(cell);}
数据对齐
希望使用这套 API 达到下面的效果
1 2 3 4 5 6 7 8 9 10 11 12+13+14 15 16 < < <public void run() { TableView tableView = new TableView(); tableView.addTitle("id"); tableView.addTitle("Catgeory"); tableView.addTitle("Name"); for (int row = 0; row < 2; row++) { tableView.addRow(); for (int col = 0; col < 3; col++) { tableView.addItem(row + "." + col); } } tableView.setContentAligmentForColumn(2, 1); // 2 代表 右对齐,1 代表 第 1 列( 从 0 开始数 ) tableView.display();}| id | Category | Name | 0.0 | 0.1 | 0.2| 1.0 | 1.1 | 1.2
LinkedList<Integer> columnContentAligments
private property
存储每一行的对齐数据
1 代表 左对齐
2 代表 右对齐
默认 左对齐
提示
你可能需要在 addTitle 里增加一些代码,让 columnContentAligments 默认为 一堆 1
void setContentAligmentForColumn(int alignment, int column)
public method
为 tableView 设置 让 column 行的对齐是 alignment
你需要在这个方法里更改 columnContentAligments 属性的值
void display()
public method
更改现有代码,结合对齐信息,打印出固定格式的结果
注意,所有标题一律左对齐,只有数据的某些行 会被 修改为 右对齐