JTable demo
?
簡單講就是在沒有使用layout manager的時(shí)候用setSize,在使用了layout manager 的時(shí)候用setPreferredSize
?
并且setPreferredSize通常和setMinimumSize、setMaximumSize聯(lián)系起來使用
setSize()是你手動(dòng)來設(shè)置組件的大小
Dimension 類封裝單個(gè)對(duì)象中組件的寬度和高度(精確到整數(shù))。該類與組件的某個(gè)屬性關(guān)聯(lián)。由 Component 類和 LayoutManager 接口定義的一些方法將返回 Dimension 對(duì)象
setPreferredSize設(shè)置此組件的首選大小
一般會(huì)用setPreferredSize?
http://www.cnblogs.com/langtianya/archive/2012/10/13/2722904.html
?
// in constructor rowSM_treatments = table_histories.getSelectionModel(); rowSM_treatments.addListSelectionListener(new ListSelectionListener() {public void valueChanged(ListSelectionEvent e) {if (e.getValueIsAdjusting()) return;ListSelectionModel lsm = (ListSelectionModel)e.getSource();if (lsm.isSelectionEmpty()) {System.out.println("No rows are selected.");} else {selectedRow_treatments = lsm.getMinSelectionIndex();System.out.println("selected Row> " + selectedRow_treatments);//do more}}});?
table.changeSelection(row, 0, false, false);
import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener;public class SelectionListener implements ListSelectionListener {JTable table;SelectionListener(JTable table) {this.table = table;}public void valueChanged(ListSelectionEvent e) {if (e.getSource() == table.getColumnModel().getSelectionModel() && table.getColumnSelectionAllowed()) {int firstRow = e.getFirstIndex();int lastRow = e.getLastIndex();// 事件處理... }}}?
| ?int | getFirstIndex() ??????????Returns the index of the first row whose selection may have changed. |
| ?int | getLastIndex() ??????????Returns the index of the last row whose selection may have changed. |
| ?boolean | getValueIsAdjusting() ??????????Returns whether or not this is one in a series of multiple events, where changes are still being made. |
| ?String | toString() ??????????Returns a String that displays and identifies this object's properties. |
??
package swing.table;import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.Date;import javax.swing.AbstractAction; import javax.swing.DefaultListSelectionModel; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener;public class SelectionModeDemo {String[] headings = { "Name", "Customer ID", "Order #", "Status" };Object[][] data = {{ "A", new Integer(3), "0", new Date() },{ "B", new Integer(6), "4", new Date() },{ "C", new Integer(9), "9", new Date() },{ "D", new Integer(7), "1", new Date() },{ "E", new Integer(4), "1", new Date() },{ "F", new Integer(8), "2", new Date() },{ "G", new Integer(6), "1", new Date() }};JTable jtabOrders = new JTable(data, headings);SelectionModeDemo() {final JFrame jfrm = new JFrame("JTable Demo");jfrm.setLayout(new FlowLayout());jfrm.setSize(800, 600);jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JScrollPane jscrlp = new JScrollPane(jtabOrders);jfrm.add(jscrlp);jtabOrders.setPreferredScrollableViewportSize(new Dimension(420, 200));// 設(shè)置選擇模式。以下列表描述了接受的選擇模式:只能選擇一行! jtabOrders.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 攔截Ctrl+A組合鍵,防止焦點(diǎn)丟失// new event create.KeyStroke ctrlA = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);// overwrite super class's event.jtabOrders.getInputMap().put(ctrlA, "DO_NOTHING");jtabOrders.getActionMap().put("DO_NOTHING", new AbstractAction() {private static final long serialVersionUID = 1L;@Overridepublic void actionPerformed(ActionEvent e) {System.out.println("Do nothing");}});/*** 在JTable里被選擇的行發(fā)生變化時(shí)處理某事件的方法。 例如: 1:選擇第一行的狀態(tài)下,選擇第二行時(shí)* 2:只選擇一行的狀態(tài)下,追加選擇另外的行時(shí)*/jtabOrders.getSelectionModel().addListSelectionListener(new ListSelectionListener() {@Overridepublic void valueChanged(ListSelectionEvent e) {DefaultListSelectionModel model = (DefaultListSelectionModel) e.getSource();if (!e.getValueIsAdjusting()) {/** public boolean getValueIsAdjusting()* 一次鼠標(biāo)的點(diǎn)擊會(huì)有兩次事件響應(yīng)(按下和釋放)。* 前者的事件屬性中g(shù)etValueIsAdjusting()=true,后者是false。* 因此,可以通過判斷getValueIsAdjusting()來區(qū)別鼠標(biāo)按下和釋放。*/JOptionPane.showMessageDialog(jfrm, "Msg:" +model.getSelectionMode() + " "+ jtabOrders.getValueAt(jtabOrders.getSelectedRow(), 0).toString());}}});jfrm.setLocationRelativeTo(null);jfrm.setVisible(true);jtabOrders.setColumnSelectionAllowed(false);jtabOrders.setRowSelectionAllowed(true);}public static void main(String args[]) {new SelectionModeDemo();} }?
?
?http://melodyvictor.blog.163.com/blog/static/1180061572011417315978/
?
//設(shè)置是否可以選擇此模型中的列。
??? jtabOrders.setColumnSelectionAllowed(false);
??? //設(shè)置是否可以選擇此模型中的行。
??? jtabOrders.setRowSelectionAllowed(true);
??? //設(shè)置此表是否允許同時(shí)存在行選擇和列選擇。
???? jtabOrders.setCellSelectionEnabled(true);
?
| static?int | MULTIPLE_INTERVAL_SELECTION ??????????selectionMode 屬性的值:一次選擇一個(gè)或多個(gè)連續(xù)的索引范圍。 |
| static?int | SINGLE_INTERVAL_SELECTION ??????????selectionMode 屬性的值:一次選擇一個(gè)連續(xù)的索引范圍。 |
| static?int | SINGLE_SELECTION ??????????selectionMode 屬性的值:一次選擇一個(gè)列表索引。 |
http://blog.csdn.net/youyigong/article/details/6830966
?
?
?
編寫該JTable的TableModel的String getColumnName(int columnIndex)方法
//傳進(jìn)來的是列的索引值
//返回該列的列名/
/給JTable設(shè)置好TableModel后,這個(gè)方法由系統(tǒng)自動(dòng)調(diào)用
//顯示在JTable中
public String getColumnName(int columnIndex){??
return "你想要設(shè)置的對(duì)應(yīng)列的列名";
}
eg.:
public String getColumnName(int columnIndex){??
if(columnIndex == 1)
return "索引值為 1 的列的名字";????
if(columnIndex == 2)
return "索引值為 2 的列的名字";??
...
}
?
?
看了一篇實(shí)現(xiàn)JTable的列寬與內(nèi)容的自適應(yīng)?稍加修飾后如下:
public void FitTableColumns(JTable myTable){JTableHeader header = myTable.getTableHeader();int rowCount = myTable.getRowCount();Enumeration columns = myTable.getColumnModel().getColumns();while(columns.hasMoreElements()){TableColumn column = (TableColumn)columns.nextElement();int col = header.getColumnModel().getColumnIndex(column.getIdentifier());int width = (int)myTable.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth();for(int row = 0; row<rowCount; row++){int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable,myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();width = Math.max(width, preferedWidth);}header.setResizingColumn(column); // 此行很重要column.setWidth(width+myTable.getIntercellSpacing().width);} }http://blog.csdn.net/qof3990/article/details/8578350
http://www.blogjava.net/zeyuphoenix/archive/2010/04/08/317755.html
?
?
?
package swing.table;import java.awt.*; import java.awt.event.*;import javax.swing.*; import javax.swing.table.TableColumnModel;public class TestTable extends JFrame {private static final long serialVersionUID = 1L;JTable tb;JPanel p = new JPanel();public TestTable() {setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocation(112, 0);setSize(700, 420);final Object[] columnNames = { "檔案號(hào)", "姓名", "年齡", "性別", "婚姻狀況", "職業(yè)", "聯(lián)系電話" };Object[][] rowData = { { "010110", "張三", "28", "男", "已婚", "教師", "13686562936" },{ "010110", "李四", "28", "男", "已婚", "教師", "13686562936" } };tb = new JTable(rowData, columnNames) {private static final long serialVersionUID = 1L;// 添加部分1public boolean isCellEditable(int row, int column) {return false;}};tb.setPreferredScrollableViewportSize(new Dimension(639, 232));// tb.setEnabled(false);tb.setRowHeight(20);tb.setRowSelectionAllowed(true);tb.setSelectionBackground(Color.lightGray);tb.setSelectionForeground(Color.white);tb.setGridColor(Color.black);tb.setShowGrid(true);tb.setShowHorizontalLines(true);tb.setShowVerticalLines(true);tb.setBackground(Color.white);// 添加部分2tb.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {if (e.getButton() == MouseEvent.BUTTON1) {// 雙擊鼠標(biāo)if (e.getClickCount() == 2) { int colummCount = tb.getModel().getColumnCount();// 列數(shù)for (int i = 0; i < colummCount; i++){System.out.print(tb.getModel().getColumnName(i)+":");System.out.print(tb.getModel().getValueAt(tb.getSelectedRow(), i).toString() + " ");}System.out.println();}}}});JScrollPane pane = new JScrollPane(tb);pane.setBackground(Color.white);p.add(pane);add(p);setVisible(true);}public static void main(String[] args) {new TestTable();} }?
加載時(shí)選中多行:
?
JTable中列的排序:
package swing.table.sort;import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.math.BigDecimal; import java.util.regex.Pattern;import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.RowSorter; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter;public class TestSortedTable {private static int flag = 0;public static void main(String args[]) {JFrame frame = new JFrame("JTable的排序測試");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);final String columnNames[] = { "ID", "姓名", "國籍", "年齡", "體重" };final Object sortRight_1st_withInt[][] = {{ 1, "嘉靖", "中國", 44, 90.5 },{ 3, "姚明", "中國", 25, 120.5 },{ 2, "趙子龍", "西蜀", 1234, 130.6 },{ 10, "曹操", "北魏", 2112, 90.0 },{ 20, "Bill Gates", "美國", 45, 0.5 },{ 5, "Tomas", "英國", 33, 100.0 }};final Object sortWrong_1st_withString[][] = {{ "1", "嘉靖", "中國", 44, "90.5" },{ "3", "姚明", "中國", 25, "120.5" },{ "2", "趙子龍", "西蜀", 1234, "130.6" },{ "10", "曹操", "北魏", 2112, "90.0" },{ "20", "Bill Gates", "美國", 45, "0.5" },{ "5", "Tomas", "英國", 33, "100.0" }};final Object[][] getRightSort_1st_withString = recoverData2Number(sortWrong_1st_withString);final DefaultTableModel model = new CustomizedTableModel(null, null);final JTable table = new JTable(model);table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);// table.setAutoCreateRowSorter(true);table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);// 只能選一行table.getTableHeader().setReorderingAllowed(false);table.setRowSorter(new TableRowSorter<TableModel>(model));JScrollPane pane = new JScrollPane(table);frame.add(pane, BorderLayout.CENTER);JButton changeSourceBtn = new JButton("Change Source");changeSourceBtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if (flag % 3 == 0) {model.setDataVector(sortRight_1st_withInt, columnNames);} else if (flag % 3 == 1) {model.setDataVector(sortWrong_1st_withString, columnNames);} else if (flag % 3 == 2) {model.setDataVector(getRightSort_1st_withString, columnNames);}flag++;}});JButton clearBtn = new JButton("Clear");clearBtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try {RowSorter<?> rowSort = table.getRowSorter();if (rowSort != null) {rowSort.setSortKeys(null);// 如果使用了排序器,先清除對(duì)表的排序 }((DefaultTableModel) table.getModel()).getDataVector().clear();((DefaultTableModel) table.getModel()).fireTableDataChanged();table.updateUI();} catch (Exception ex) {System.out.println(ex);}}});JPanel southPanel = new JPanel();southPanel.setLayout(new FlowLayout());southPanel.add(changeSourceBtn);southPanel.add(clearBtn);frame.add(southPanel, BorderLayout.SOUTH);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(600, 300);frame.setVisible(true);frame.setLocationRelativeTo(null);}private static Object[][] recoverData2Number(Object[][] sortWrong_1st_withString) {Object[][] target = new Object[sortWrong_1st_withString.length][];for (int i = 0; i < sortWrong_1st_withString.length; i++) {Object[] sourceRecord = sortWrong_1st_withString[i];Object[] targetRecord = new Object[sourceRecord.length];for (int j = 0; j < sourceRecord.length; j++) {Object item = sourceRecord[j];if (isNumericInt(sourceRecord)) {item = Integer.parseInt(item.toString());} else if (isNumericDouble(item)) {item = new BigDecimal(item.toString()).doubleValue();}targetRecord[j] = item;}target[i] = targetRecord;}return target;}private static boolean isNumericInt(Object valueAt) {Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");return pattern.matcher(valueAt.toString().trim()).matches();}private static boolean isNumericDouble(Object valueAt) {Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*\\.?[\\d]*$");return pattern.matcher(valueAt.toString().trim()).matches();}}class CustomizedTableModel extends DefaultTableModel {private static final long serialVersionUID = 1L;public Class<?> getColumnClass(int column) {if (getRowCount() == 0) {return Object.class;}return getValueAt(0, column).getClass();}public CustomizedTableModel(Object[][] data, Object[] columnNames) {super(data, columnNames);}}排序有兩個(gè)途徑:
(1)為每列的值設(shè)置正確的類型,并且重寫DefaultTableModel中的getColumnClass方法
因?yàn)镮nteger,Double實(shí)現(xiàn)了Comparator接口,即可正確排序
(2)table.setRowSorter(new TableRowSorter<TableModel>(model));
然后為每列指定特定的Comparator:
定義表的時(shí)候,選擇按自定義算法排序的字段,如果不設(shè)置,默認(rèn)按字符串的ASCII碼排序
JTable dataGrid=new JTable ();DefaultTableModel model = (DefaultTableModel) this.dataGrid.getModel(); TableRowSorter<TableModel> sorter=new TableRowSorter<TableModel>(model); //sorter.setSortable(0, false); sorter.setComparator(0, new cimframe.util.OrderNumberComparator()); sorter.setComparator(3, new cimframe.util.OrderNumberComparator()); sorter.setComparator(4, new cimframe.util.OrderNumberComparator()); sorter.setComparator(5, new cimframe.util.OrderNumberComparator()); dataGrid.setRowSorter(sorter);
一個(gè)關(guān)于SWING的工程,當(dāng)然會(huì)用到大量的表格最早清空表格是這樣寫的
//??????????????? DefaultTableModel model = (DefaultTableModel) table.getModel();
//??????????????? for (int i = model.getRowCount() - 1; i >= 0; i--) {
//??????????????????? model.removeRow(i);
//??????????????? }??
用這個(gè)方法是有問題的,因?yàn)槭荍Table??? >> TableModel? >> TableData(Vector或String[])這樣的映射關(guān)系,如果用上面的方法,如果數(shù)據(jù)增加或減少都不會(huì)通知TableModel ,就導(dǎo)致每次清數(shù)據(jù)就報(bào)數(shù)據(jù)越界異常ArrayIndexOutOfBoundsException。
?
如果直接清理數(shù)據(jù)是會(huì)通知上層的監(jiān)聽,改變模型
((DefaultTableModel) table.getModel()).getDataVector().clear();?? //清除表格數(shù)據(jù)
((DefaultTableModel) table.getModel()).fireTableDataChanged();//通知模型更新
table.updateUI();//刷新表格
?
這樣做了,程序好像是不出問題了,但是如果對(duì)表格做了排序操作,再看看,程序是不出錯(cuò)了,但是每加載一行,就看到表格會(huì)做一次排序,這個(gè)過程的開銷很大,如果數(shù)據(jù)量大的話,甚至導(dǎo)致內(nèi)存溢出。經(jīng)過一天半的研究,跟蹤,終于找到了問題所在,創(chuàng)建表的時(shí)候,引用了排序器,排序器的監(jiān)聽是一個(gè)獨(dú)立于JTable >> TableModel >> TableData之外,又在后臺(tái)影響著這三者之間的關(guān)系的一個(gè)人,在程序調(diào)試時(shí),很難找到他在那里影響的,最終在JDK API里發(fā)現(xiàn)了一點(diǎn)端倪
javax.swing
類 RowSorter<M>
java.lang.Objectjavax.swing.RowSorter<M>
類型參數(shù): M - 底層模型的類型 ?setSortKeys
public abstract void setSortKeys(List<? extends RowSorter.SortKey> keys) 設(shè)置當(dāng)前排序鍵。 參數(shù): keys - 新的 SortKeys;null 是指定一個(gè)空列表的簡寫,表示視圖應(yīng)該是未排序的。 toggleSortOrder public abstract void toggleSortOrder(int column)如果此方法導(dǎo)致更改排序順序和排序操作,則它將發(fā)送適當(dāng)?shù)?RowSorterListener 通知。
?
上面這兩個(gè)方法很像,但又有區(qū)別,我先用toggleSortOrder(int column) 這個(gè)column必須有一個(gè)有效的列號(hào),就是說,不能用-1,這個(gè)方法是不能取消對(duì)表的排序選中的。那么另一個(gè)方法setSortKeys(List<? extendsRowSorter.SortKey> keys),這個(gè)就比較難了,我也不知道應(yīng)該傳什么參數(shù),再看參數(shù)說明:null 是指定一個(gè)空列表的簡寫,表示視圖應(yīng)該是未排序的?!皯?yīng)該”兩字說的實(shí)在是詭異,我就把它當(dāng)成死馬醫(yī),看看到底行不行,嘿嘿,通過方法:rowSort.setSortKeys(null);把表格還原到不排序的狀態(tài),就達(dá)到我想要的結(jié)果了,大功終于告成!
http://blog.csdn.net/aptweasel/article/details/7028058
?
http://www.cnblogs.com/tianyaxue/p/3494291.html
http://jingyan.baidu.com/article/fedf07377f003035ac8977c3.html
?
Java JTable 點(diǎn)擊表頭,能不能進(jìn)行多列排序
?
轉(zhuǎn)載于:https://www.cnblogs.com/softidea/p/4535890.html
總結(jié)
以上是生活随笔為你收集整理的JTable demo的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于Shell的一些常用命令
- 下一篇: PHP多进程处理并行处理任务实例