Re: [問題] 如何同步兩個JTable的JTableHeader
※ 引述《mrker (ꬮ....)》之銘言:
: 抱歉... 小弟又有問題了...
: 承之前的描述 我最後是使用
: table1.getTableHeader()
: .setColumnModel(table2.getTableHeader().getColumnModel());
: 讓兩個JTable的ColumnModel為一致
: 但會造成一個情況
: 譬如說某個欄位(假設是性別),我希望做到
: if ("MALE".equals(sex))
: 欄位.setBackground(Color.BLUE);
: else if ("FEMALE".equals(sex))
: 欄位.setBackground(Color.RED);
: 但問題來了,兩個JTable共用一個ColumnModel,
: 會致使兩邊cell的任何UI異動,都會同步
: 因此問題又回到原點了,必須在TableHeader上做處理
: (因為對我的需求來說兩邊Header部分沒有差異)
: 可以...再麻煩 指點一下嗎? 謝謝 Orz
你的意思是你希望兩個 table 內的對應的 column 所使用的 cell renderer
是各自獨立的?
column model 所管理的 table column 可以指定該 column 所要使用的 cell
renderer,但這個屬性可以是 null,故 JTable 本身還有另一個機制去決定
各 column 要怎麼做 rendering。
當 table column 本身沒有指定 cell renderer 時,JTable 另外會依照
column 所持有的數據的形態來決定該使用哪一個 cell renderer。
http://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html#setDefaultRenderer(java.lang.Class, javax.swing.table.TableCellRenderer)
建議你可以試著不要直接對 TableColumn 去設置 cell renderer,而是對 JTable
去設置 default renderer,適當配合 table model,是可以做到 JTable 內任一個
column 所使用的 cell renderer。
這種以 data type 來決定所使用的 cell renderer 的做法有時會有些麻煩,比如說
就數據的特性來說,某兩個 column 都是 Integer,而你要這兩個 column 以不同
的方式顯示數據,若你指定 Integer.class 的 default renderer 為 R,則 R 會
被拿來 render 這兩個 column,要嘛你可能採取讓 table model 回報其中一個
column 的 type 為 Object.class 來避開(這個解法會影響到其他是 Object type
的 column);要嘛你在 cell renderer 裡多下點功夫(render 會依據 rendered
cell 所處的 column index 來處理)。
如果對 JTable 內的 cell 外觀做客製化是很重要,且其份量也高的話,我建議
你考慮使用 SwingX(https://swingx.java.net),他的 JXTable 是以 highlighter
來 decorate cell 的外觀,而 cell 是否要 highlight 的條件與特定 highlight
的 decoration 方式是分成兩個 aspect 去做,加上 hightlighter 可以混搭,
理論上再複雜的客製工作都做得出來。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.166.238.27
推
12/09 17:45, , 1F
12/09 17:45, 1F
推
12/09 17:50, , 2F
12/09 17:50, 2F
推
12/12 22:25, , 3F
12/12 22:25, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 6 之 6 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章