※設定欄位的寬度
JTable的預設值是所有欄位的寬度都一樣,我們可以透過 setPreferredWidth
來設定每個欄位自己的寬度。
/* JTableDemo.java
* Created on 2008/9/5
* Author Tony
* Blog tonybox
*/import java.awt.*;
import javax.swing.*;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;public class JTableDemo2 extends JFrame {
String[] columnNames = {“姓名", “性別", “嗜好", “年齡", “是否抽煙"};
Object[][] data = {
{“張大同", “男", “看書", new Integer(15), new Boolean(false)},
{“李小婷", “女", “逛街", new Integer(19), new Boolean(false)},
{“陳小明", “男", “打電動", new Integer(13), new Boolean(false)},
{“王小華", “男", “打籃球", new Integer(20), new Boolean(false)},
{“孫小毛", “男", “被人扁", 45, true}};JTableDemo2(){
super(“JTable Demo 2″);
Container c = getContentPane();
c.setLayout(new BorderLayout());JTable table = new JTable(data,columnNames);
table.setFillsViewportHeight(false);
JScrollPane tscroll = new JScrollPane(table);//取得這個table的欄位模型
TableColumnModel cModel = table.getColumnModel();//取得這個table某個欄位的資訊
TableColumn columnName = cModel.getColumn(0);
TableColumn columnSex = cModel.getColumn(1);
TableColumn columnAge = cModel.getColumn(3);//個別設定偏好的寬度
columnName.setPreferredWidth(200);
columnSex.setPreferredWidth(50);
columnAge.setPreferredWidth(50);c.add(tscroll,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}public static void main(String[] args) {
new JTableDemo2();
}}
參考資料:http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
請問要怎麼取得欄位寬度呢?
如果是使用者變更的
以我寫的範例來說,可以這麼寫
cModel.getColumn(0).getWidth();
如此會取得第1個欄位的寬度,如果要動態偵測的話,
可以使用 TableColumnModelListener 去取得使用者改變欄寬的事件
Simply want to say your article is as surprising. The clearness in your post is simply nice and i can
assume you’re an expert on this subject. Fine with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please continue the gratifying work.
It’s a shame you don’t have a donate button! I’d without a doubt donate to this fantastic blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will talk about this blog with my Facebook group. Talk soon!