jtable 滑鼠點擊事件 |
答題得分者是:neoart
|
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
|
neoart
版主 發表:22 回覆:582 積分:425 註冊:2003-05-09 發送簡訊給我 |
如果沒有特別的設定的話,照理說click在某jtable格內(cell)時,除了該格是呈現編輯(editing ,也就是你可以更改格內資料)狀態之外,該列的其他格都是
呈現被選取(selected)狀態 如果你不希望jtable內容可以被修改的話,可以直接覆蓋 "isCellEditable(int row,int col)" 函數 承我上次的例子 ======================================================================================= MyCalssTable jTable1=null; { jTable1=new MyCalssTable (vctRows,vctColumn); //產生一個 4個欄位,10列的table ... ... ... jScrollPane1.getViewport().add(jTable1, null); //加入 jscrollpanel jTable1.addMouseListener(new MouseAddp()); // add mouse listener } //-------------mouse event handler----------------------------------------------- public class MouseAddp extends java.awt.event.MouseAdapter{ public void mouseClicked(java.awt.event.MouseEvent me){ if(me.getClickCount()==2){ //<--- this is dobule click int row=jTable1.getSelectedRow(); System.out.println(" row " row "Double Clicked!!!"); ....呼叫你的Double Click事件吧.... } } } ---------------------------------------宣告一個內部類別,當然你可以放在其他package之中,以供日後引用--------------- public class MyCalssTable extends javax.swing.JTable{ //只要覆蓋我們用的到的建構元 public MyCalssTable(Vector vct,Vector vcg2){ super(vct,vcg2); } //只要覆蓋我們用的到的函數 public boolean isCellEditable(int row,int col){ return false; // 所有的格子皆不可修改 } } ----------------------------------------------------------------------------------------------------------------------------------------------------- ======================================================================================== |
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
謝謝版主!!我的問題有得到大概的解決,不過因為在跟老師的討論下又出現了一些問題!!
1. 在另外一支class裡在將呼叫服務後所傳回的值包成了一個hashmap,然後我在Jtable的程式中我要抓到那包hashmap的值並讓他顯是在我的jtable上,可是我遇到的問題是,在同一個鍵值名稱會有多個值那我要怎麼讓他對應到jtable的欄位,例如我用一張銷售訂單去呼叫服務然後回傳有很多張採購單,但是每張採購單的項目都一樣只是值不一樣,我要怎麼讓他一筆一筆的呈現在jtable上,下面是我寫的片段 public ConnectionTable(HashMap dataMap) { initComponents(); this.tempMap = dataMap; } public void setTableData() { tabData.setValueAt((String) tempMap.get("SITEID"), 0, 0); tabData.setValueAt((String) tempMap.get("SONO"), 0, 1); tabData.setValueAt((String) tempMap.get("SALESTYPEID"), 0, 2); tabData.setValueAt((String) tempMap.get("ENTITYID"), 0, 3); tabData.setValueAt((String) tempMap.get("ISSUEDATE"), 0, 4); tabData.setValueAt((String) tempMap.get("SALESORDERDATE"), 0, 5); tabData.setValueAt((String) tempMap.get("CLOSEDATE"), 0, 6); tabData.setValueAt((String) tempMap.get("BILLTOCUSTOMERID"), 0, 7); tabData.setValueAt((String) tempMap.get("SODETAILSCHEDULEDDELIVERYDATE"), 0, 8); tabData.setValueAt((String) tempMap.get("SODETAILSALESORDERAMOUNT"), 0, 9); } 我該怎麼去辨別hashmap中同一個鍵值名稱卻是屬於不同筆資料的 2.現在老師希望我點了jtable的某一筆料後所觸發的事件是把table的值都顯現到介面上相對應的textfiled裡面 我大概知道是要去抓jtable每個欄位的值在放到textfiled中,是用getvalueat()嗎可試要怎麼放到對應的textfiled裡面我就不會了!! 還是我可以用剛剛包來的hashmap裡的值呢 再次麻煩各位了!!! |
neoart
版主 發表:22 回覆:582 積分:425 註冊:2003-05-09 發送簡訊給我 |
1.鍵值一定要不同,哪家資料庫會有key duplicat的嗎? 如果是從資料庫select出來的,何不直接用資料列的pk呢?
(別跟我說你沒有放在資料庫....還是你的data table是沒有設primary key !?) 如果真的這麼"姑不而將"的話,可以考慮用更多的欄位加別的特殊字元做key ex String key=record.get(colm1).toString() '|' record.get(colm2).toString() ..... myHashtable.put(key,record); 還是你想用同一個key值找出相同key的物件?那你就要考慮把同一個key的物件放在陣列等容器,再把此容器放入hashtable/hash map 中 2.你已經知道是getValueAt(row,col) 了,不是嗎? Object objValue=myTable.getValueAt(row,col); xxxTextField.setText((objValue==null)?"":objValue.toString()); 3. 取值,是要用view (gui,也就是你的table)上的值,還是Model(data,也就是你的map)中的值 ?,就你的例子(table is not editable) 而言是一樣, 不過,如果你的例子是table格子可以編輯的話, 那還是以table中的cell value為標準--因為沒有update到實體資料的話,就依現狀(gui)為準. P.S.放假就要出去玩,帶女友走走,別再codding了,想寫程式,以後機會多的是
編輯記錄
neoart 重新編輯於 2008-10-10 11:08:52, 註解 無‧
|
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
我用了其他方式去寫,遇到另一個問題了,回傳的時候她是一個arrayList然後裡面是很多筆資料,我要怎樣把它包成一個hashmap,我只知道要寫一個for迴圈,可是不知道怎麼去做,然後放到jTable的部分我有寫了,就差這個地方,return poNoList;這個是我要包成hashmap的list然後要給下面的程式用,拜託幫幫我了!!困擾很久,感覺總是會有盲點!! 謝謝了~~
public void setMultiTableData(ArrayList dataList) { for(int i = 0; i < dataList.size(); i ) { HashMap map = (HashMap) dataList.get(i); setTableData(map); } } public void setTableData(HashMap dataMap) { Object[] obj = { dataMap.get("SITEID"), dataMap.get("SONO"), dataMap.get("SALESTYPEID"), dataMap.get("ENTITYID"), dataMap.get("ISSUEDATE"), dataMap.get("SALESORDERDATE"), dataMap.get("CLOSEDATE"), dataMap.get("BILLTOCUSTOMERID"), dataMap.get("SODETAILSCHEDULEDDELIVERYDATE"), dataMap.get("SODETAILSALESORDERAMOUNT") }; model.addRow(obj);
編輯記錄
bomaboy 重新編輯於 2008-10-13 20:52:00, 註解 無‧
|
neoart
版主 發表:22 回覆:582 積分:425 註冊:2003-05-09 發送簡訊給我 |
TreeMap list2Map(java.util.List _list){ TreeMap hm=new TreeMap(); for( int i=0;i<_list.getSize();i ){ hm.put(String.ValueOf(i),_list.get(i)); // 直接以序號做key } } .... ... ... public void map2Tbl(TreeMap _map){ Iterator itrKey=_map.keySet().iterator(); while(itrKey.hasNext()){ Object objKey=itrKey.next(); Object rowData=_map.get(objKey); Object[] obj ={ rowData.get("SITEID"), rowData.get("SONO"), rowData.get("SALESTYPEID"), rowData.get("ENTITYID"), rowData.get("ISSUEDATE"), rowData.get("SALESORDERDATE"), rowData.get("CLOSEDATE"), rowData.get("BILLTOCUSTOMERID"), rowData.get("SODETAILSCHEDULEDDELIVERYDATE"), rowData.get("SODETAILSALESORDERAMOUNT") }; model.addRow(obj); } } |
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
|
neoart
版主 發表:22 回覆:582 積分:425 註冊:2003-05-09 發送簡訊給我 |
|
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
不好意思是我太急了!!現在程式可以跑可是TABLE沒有抓到LIST,不知道是哪邊出了差錯
程式一、我是要抓她的poList,我在她的MAIN裡呼叫了我TABLE的程式 程式二、這是我TABLE的程式 package ConvertDocument; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JOptionPane; import tw.com.lancer.team.constant.usecase.core.product.UC_CORE_BOM; import tw.com.lancer.team.constant.usecase.core.product.UC_CORE_ITEM; import tw.com.lancer.team.constant.usecase.distribution.distribution.UC_DIS_SALESORDER; import tw.com.lancer.team.constant.usecase.manufacture.work.UC_MFG_WORKORDER; import tw.com.lancer.team.constant.usecase.purchase.purchase.UC_PUR_PURCHASEORDER; import tw.com.lancer.team.gui.framework.delegate.LCBusinessDelegate; import tw.com.lancer.team.gui.framework.utilities.test.LCTestBasicFrame; /* * @author user * @建立日期 2008/9/20 下午 9:38:11 */ /** * TODO 請說明此程式的責任或功能 * * @version $Revision: 1.0 $ * * @author Lancermailto:neo@mail.lancer.com.tw">Lancer> * */ public class OneSOtoManyPO { //在按下確認SO(銷售訂單)鈕時執行本方法, 產出WO的材料全是backflush public ArrayList convertOneSOtoManyPO(String entityID, String soNo) { BigDecimal zero = new BigDecimal(0); BigDecimal one = new BigDecimal(1); JOptionPane jo = new JOptionPane(); ArrayList poNoList = new ArrayList(); ArrayList poList = new ArrayList(); HashMap qrySoInputMsg = new HashMap(); HashMap qrySoOutputMsg = new HashMap(); HashMap crtPoInputMsg = new HashMap(); HashMap crtPoOutputMsg = new HashMap(); //組qrySoInputMsg qrySoInputMsg.put("ENTITYID", entityID); qrySoInputMsg.put("MINSONO", soNo); qrySoInputMsg.put("MAXSONO", soNo); //呼叫服務找SO的內容 qrySoOutputMsg = (HashMap)LCBusinessDelegate.getInstance().send( UC_DIS_SALESORDER.name, UC_DIS_SALESORDER.QRYSALESORDERBYMERGE, qrySoInputMsg); if (qrySoOutputMsg.get("RETURNVALUE").toString().equals("N")) { jo.showMessageDialog(jo, "呼叫服務UC_DIS_SALESORDER.QRYSALESORDERBYMERGE失敗" "\n" qrySoOutputMsg.get("RETURNMSG").toString()); return null; } //產生一群PO ArrayList soList = (ArrayList) qrySoOutputMsg.get("DATA"); if (soList.size() == 0) { jo.showMessageDialog(jo, "SONO没有銷售項目"); return null; } for (int i=0; i //產生一張PO主檔資料 HashMap aSoMap = (HashMap) soList.get(i); //組crtPoInputMsg String siteID = aSoMap.get("SITEID").toString(); crtPoInputMsg.put("SITEID", siteID); String issueDate = aSoMap.get("ISSUEDATE").toString(); crtPoInputMsg.put("ISSUEDATE", issueDate); String issueEmployeeID = aSoMap.get("ISSUEEMPLOYEEID").toString(); crtPoInputMsg.put("ISSUEEMPLOYEEID", issueEmployeeID); crtPoInputMsg.put("PURCHASEORDERDEPARTMENTID", aSoMap.get("SALESDEPARTMENTID").toString()); crtPoInputMsg.put("PURCHASEEMPLOYEEID", aSoMap.get("ISSUEEMPLOYEEID").toString()); crtPoInputMsg.put("PURCHASETYPEID", aSoMap.get("SALESTYPEID").toString());//事先都訂為normal crtPoInputMsg.put("VENDORID", "zzz");//由使用者自行決定 crtPoInputMsg.put("PAYMENTTERMID", "internal");//default crtPoInputMsg.put("TAXTYPEID", aSoMap.get("TAXTYPEID")); crtPoInputMsg.put("TAXCHARGETYPE", aSoMap.get("TAXCHARGETYPE")); crtPoInputMsg.put("ISTAXINCLUDE", "N"); crtPoInputMsg.put("CURRENCYID", aSoMap.get("CURRENCYID")); crtPoInputMsg.put("PURCHASEORDERAMOUNT", zero);//to be determined crtPoInputMsg.put("EXCHANGERATE", one);//local purchase crtPoInputMsg.put("PAYMENTSITEID", aSoMap.get("SITEID")); crtPoInputMsg.put("ISCALCULATEPURCHASEQUOTA", "N"); String soItemID = aSoMap.get("ITEMID").toString(); String aDate = aSoMap.get("SALESORDERDATE").toString(); BigDecimal qty = (BigDecimal)aSoMap.get("SALESORDERQUANTITY"); String bomID = aSoMap.get("ITEMID").toString();//assume the same as item HashMap qryBomInput = new HashMap(); qryBomInput.put("ENTITYID", aSoMap.get("ENTITYID")); qryBomInput.put("BOMID", bomID); HashMap qryBomOutput = (HashMap)LCBusinessDelegate.getInstance().send( UC_CORE_BOM.name, UC_CORE_BOM.QRYBOMITEM, qryBomInput); if (qryBomOutput.get("RETURNVALUE").toString().equals("N")) { jo.showMessageDialog(jo, "呼叫服務QRYBOMITEM失敗" "\n" qryBomOutput.get("RETURNMSG").toString()); return null; } ArrayList bomList = (ArrayList) qryBomOutput.get("DATA"); if (bomList.size() == 0) { jo.showMessageDialog(jo, "產生PO時發現没有材料表資料"); return null; } for (int j=0; j ArrayList poDetailList = new ArrayList(); HashMap crtPoDetailInputMsg = new HashMap(); HashMap crtPoDetailOutputMsg = new HashMap(); HashMap aMaterial = (HashMap) bomList.get(j); crtPoDetailInputMsg.put("SEQUENCENO", "0010"); String componentItemID = aMaterial.get("ITEMID").toString(); //Query basic item attributes HashMap qryBasicItemInput = new HashMap(); HashMap qryBasicItemOutput = new HashMap(); qryBasicItemInput.put("ITEMID", componentItemID); qryBasicItemOutput = (HashMap)LCBusinessDelegate.getInstance().send( UC_CORE_ITEM.name, UC_CORE_ITEM.QRYBASICITEM, qryBasicItemInput); if (qryBasicItemOutput.get("RETURNVALUE").toString().equals("N")) { jo.showMessageDialog(jo, "呼叫服務UC_CORE_ITEM.QRYITEM失敗" "\n" qryBasicItemOutput.get("RETURNMSG").toString()); return null; } ArrayList itemList = (ArrayList) qryBasicItemOutput.get("DATA"); if (itemList.size() == 0) { jo.showMessageDialog(jo, "件號不存在"); return null; } HashMap anItemMap = (HashMap) itemList.get(0); crtPoDetailInputMsg.put("ITEMID", componentItemID); crtPoDetailInputMsg.put("ITEMNAME", anItemMap.get("ITEMNAME")); crtPoDetailInputMsg.put("ITEMSPECIFICATION", anItemMap.get("SPECIFICATION"));//default crtPoDetailInputMsg.put("SCHEDULEDDELIVERYDATE",aDate); BigDecimal purQty = qty.multiply((BigDecimal)aMaterial.get("QUANTITYPERUNIT")); crtPoDetailInputMsg.put("INVENTORYUMID", aSoMap.get("INVENTORYUMID")); crtPoDetailInputMsg.put("PURCHASEREQUESTQUANTITY", purQty); crtPoDetailInputMsg.put("PURCHASEORDERUMID", aSoMap.get("INVENTORYUMID")); crtPoDetailInputMsg.put("PURCHASEORDERQUANTITY", purQty); crtPoDetailInputMsg.put("MINORDERQUANTITY", zero); crtPoDetailInputMsg.put("ORDERMULTIPLYER", one); crtPoDetailInputMsg.put("PURCHASEORDERPRICEUMID", aSoMap.get("INVENTORYUMID")); crtPoDetailInputMsg.put("UNITPRICE", zero);//to be determined crtPoDetailInputMsg.put("UNITPRICESTATUS", "UnConfirmed");//to be determined crtPoDetailInputMsg.put("PURCHASEORDERAMOUNT", zero);//to be determined crtPoDetailInputMsg.put("RECEIVINGSITEID", aSoMap.get("SITEID")); crtPoDetailInputMsg.put("RECEIVINGWAREHOUSEID", aSoMap.get("SHIPPINGWAREHOUSEID")); crtPoDetailInputMsg.put("SOURCETYPE", "Unplan");//unplan crtPoDetailInputMsg.put("DETAILSTATUS", "00");//open poDetailList.add(crtPoDetailInputMsg); crtPoInputMsg.put("PURCHASEORDERDETAIL", poDetailList); //呼叫服務產生一張PO crtPoOutputMsg = (HashMap)LCBusinessDelegate.getInstance().send( UC_PUR_PURCHASEORDER.name, UC_PUR_PURCHASEORDER.CRTPURCHASEORDER, crtPoInputMsg); if (crtPoOutputMsg.get("RETURNVALUE").toString().equals("N")) { jo.showMessageDialog(jo, "呼叫服務UCRTPURCHASEORDER失敗" "\n" crtPoOutputMsg.get("RETURNMSG").toString()); return null; } poList.add(crtPoOutputMsg); // poNoList.add(crtPoOutputMsg.get("PONO")); } } return poList; } /* HashMap qryBasicItemOutput = new HashMap(); ArrayList itemList = (ArrayList) qryBasicItemOutput.get("DATA"); for (int i=0 ; i < itemList.size; i ) { HashMap map = (HashMap) itemList.get(i); map.put(map.get("SONO"), map); } */ public static void main(String[] args) { //LCTestBasicFrame frame = new LCTestBasicFrame();//測試時登入NEO使用 String entityID = "century"; String soNo = "SO0810000364";//一定要確認狀態的SO單才行 OneSOtoManyPO conversion = new OneSOtoManyPO(); ArrayList poNoList = conversion.convertOneSOtoManyPO(entityID, soNo); ConnectionTablePO ctpo = new ConnectionTablePO(); ArrayList poList = conversion.convertOneSOtoManyPO(entityID, soNo); //ConnectionTablePO ctpo = new ConnectionTablePO(); ctpo.setMultiTableData(poList); for (int i=0; i System.out.println("PO Number = " poNoList.get(i).toString()); } } } package ConvertDocument; /* * @author bomaboy * @建立日期 2008/10/12 下午 10:38:50 */ /** * TODO 請說明此程式的責任或功能 * * @version $Revision: 1.0 $ * * @author Lancermailto:neo@mail.lancer.com.tw">Lancer> * */ import java.awt.event.*; import java.awt.Rectangle; import java.sql.*; import java.util.*; import java.util.logging.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; /** * * @author Null */ public class ConnectionTablePO extends javax.swing.JFrame implements TableModelListener { //連接字串 /* String connectionUrl = "jdbc:sqlserver://localhost:1433;" "databaseName=Accounting;user=sa;password=bomaboy;"; Connection con; Statement stmt; ResultSet rs; ResultSetMetaData rsm; */ CompositeUI ui; String[] columnNames = null; //列標題 Object[][] data = null; //資料項 DefaultTableModel model; //表格模型 HashMap tempMap2; /** Creates new form ConnectionSQL */ public ConnectionTablePO(CompositeUI ui) { this.ui = ui; initComponents(); this.setLocationRelativeTo(null); } public ConnectionTablePO() { } public void setTempMap2(HashMap tempMap2) { this.tempMap2 = tempMap2; } public ConnectionTablePO(HashMap dataMap) { initComponents(); this.tempMap2 = dataMap; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ public void setMultiTableData(ArrayList poList) { for(int i = 0; i < poList.size(); i ) { HashMap map = (HashMap) poList.get(i); setTableData(map); } } public void setTableData(HashMap dataMap) { Object[] obj = { dataMap.get("SITEID"), dataMap.get("PONO"), dataMap.get("PURCHASEORDERQUANTITY"), dataMap.get("ISSUEDATE"), dataMap.get("PURCHASEORDERDEPARTMENTNAME"), dataMap.get("CLOSEDATE"), dataMap.get("VENDORNAME"), dataMap.get("PURCHASEORDERAMOUNT"), }; model.addRow(obj); } private void initComponents() { //cmdConnection = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tabData = new javax.swing.JTable(); //cmdAddRow = new javax.swing.JButton(); //cmdDelRow = new javax.swing.JButton(); // cmdClose = new javax.swing.JButton(); tabData.setColumnSelectionAllowed(false); tabData.setRowSelectionAllowed(true); tabData.setCellSelectionEnabled(true);//使得表格的選取是以cell爲單位, tabData.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tabData.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseReleased(MouseEvent e) { if (e.getClickCount() == 2) { System.out.println("aaaa"); PurchaseOrderInterface poui = new PurchaseOrderInterface(); int selectRow = tabData.getSelectedRow(); HashMap tranMap = (HashMap) tempMap2.get((String) tabData.getValueAt(selectRow, 1)); poui.setPoUI(ui, tranMap); //int selectRow = tabData.getSelectedRow(); //setTextData(selectRow); //tabData.getValueAt(row, column) } } public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} }); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("SQL連結"); cmdConnection.setText("連接/顯示"); /* cmdConnection.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdConnectionActionPerformed(evt); } }); */ tabData.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null}, {null, null, null, null,null, null, null, null} }, new String [] { "營運點名稱", "採購單號", "採購數量", "開立日期","採購人員姓名","結案日期","廠商名稱" , "採購金額"} )); jScrollPane1.setViewportView(tabData); //tabData.setEnabled(false); //cmdAddRow.setText("添加行"); /* cmdAddRow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdAddRowActionPerformed(evt); } }); */ //cmdDelRow.setText("刪除行"); /* cmdDelRow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdDelRowActionPerformed(evt); } }); */ //cmdClose.setText("關閉"); //cmdClose.addActionListener(new java.awt.event.ActionListener() { //public void actionPerformed(java.awt.event.ActionEvent evt) { //cmdCloseActionPerformed(evt); //} //}); //javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); setLayout(layout); setBounds(new Rectangle(0, 20, 1011, 130)); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) //.addComponent(cmdConnection) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) //.addComponent(cmdAddRow) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) //.addComponent(cmdDelRow) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) //.addComponent(cmdClose, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(203, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) // .addComponent(cmdConnection) //.addComponent(cmdAddRow) //.addComponent(cmdDelRow) //.addComponent(cmdClose) ) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)) ); pack(); }// //GEN-END:initComponents private void cmdConnectionActionPerformed(java.awt.event.ActionEvent evt) //GEN-FIRST:event_cmdConnectionActionPerformed { // TODO add your handling code here: //連接初始化表格 /* try { //連接驅動 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException ex) { Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE, null, ex); } try { con = DriverManager.getConnection(connectionUrl); //設置資料庫可以更新 stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //查詢 rs = stmt.executeQuery("select * from AP"); rsm = rs.getMetaData(); //判斷可以對資料庫的更新 if (rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE) { System.out.println("Can UPDATABLE"); } else { System.out.println("Only Ready"); } //獲得列標題 columnNames = new String[rsm.getColumnCount()]; for (int i = 0; i < rsm.getColumnCount(); i ) { columnNames[i] = rsm.getColumnName(i 1); } int row = 0; int colum = 0; int columCount = rsm.getColumnCount(); //獲取行數先移動到尾端,獲取行號,即為行數,然後再移回來 rs.last(); int rowCount = rs.getRow(); rs.beforeFirst(); //讀取資料到資料的變動量 data = new Object[rowCount][columCount]; while (rs.next()) { for (colum = 0; colum < rsm.getColumnCount(); colum ) { data[row][colum] = rs.getObject(colum 1); } row ; } //rs.close(); //stmt.close(); //con.close(); } catch (SQLException ex) { Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE, null, ex); } */ //初始化資料模型 model = new DefaultTableModel(data, columnNames) { /** * 重寫 getColumnClass * 可以使表格自動識別資料類型 */ @Override public Class getColumnClass(int c) { //對空資料集進行檢驗 if (dataVector.isEmpty() == false && getValueAt(0, c)!=null) { return getValueAt(0, c).getClass(); } else { return Object.class; } } }; // implements TableModelListener,才能獲取 tableChanged(TableModelEvent e) 事件 model.addTableModelListener(this); //設置表格模型 tabData.setModel(model); //單及標題檔排序 RowSorter tabData.setRowSorter(sorter); }//GEN-LAST:event_cmdConnectionActionPerformed /* private void cmdAddRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAddRowActionPerformed //添加新行 try { //載資料模型加入一個空的 Vector,就能實現空行的顯示 model.addRow(new Vector()); //資料及的增加 rs.moveToInsertRow(); //初始化資料,這裡第一列是非空的,所以隨機產生一個資料 rs.updateObject(1, (int) (System.currentTimeMillis() % 10000)); //將新行寫入資料庫 rs.insertRow(); } catch (SQLException ex)//GEN-LAST:event_cmdAddRowActionPerformed { Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE, null, ex); } } private void cmdDelRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDelRowActionPerformed //由於使用排序,選折的行和數據集中對應的行可能序號不同 //需要轉換一下看一下代碼 int select = tabData.getSelectedRow(); if (select == -1) { return; } //轉換表格選擇的行號到資料模型的行號 select = tabData.getRowSorter().convertRowIndexToModel(select); try { //定位到絕對行號,這個內容和資料模型同步 rs.absolute(select 1); rs.deleteRow(); model.removeRow(select); } catch (SQLException ex)//GEN-LAST:event_cmdDelRowActionPerformed { Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE, null, ex); } } private void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCloseActionPerformed try { //關閉連接 rs.close(); stmt.close(); con.close(); } catch (SQLException ex) { Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE, null, ex); } } */ //GEN-LAST:event_cmdCloseActionPerformed /* * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } new ConnectionSQL().setVisible(true); } }); } //取得tabData物件 public JTable getTabData() { return this.tabData; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cmdAddRow; private javax.swing.JButton cmdClose; private javax.swing.JButton cmdConnection; private javax.swing.JButton cmdDelRow; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tabData; // End of variables declaration//GEN-END:variables public void tableChanged(TableModelEvent e) { /* //資料改變後的操作 System.out.println(e.getFirstRow() ":" e.getColumn()); //e.getColumn() == -1,表示插入新行 if (e.getColumn() != -1) { Object o; //這兩列是兩個成績,修改後更新成績和幾個判斷 if (e.getColumn() == 3 || e.getColumn() == 4) { //獲取某個資料 o = tabData.getValueAt(e.getFirstRow(), 3); int a = 0; //空檢查 if (o != null) { a = Integer.valueOf(o.toString()); } o = tabData.getValueAt(e.getFirstRow(), 4); if (o != null) { a = Integer.valueOf(o.toString()); } //設置某個格的資料 tabData.setValueAt(a, e.getFirstRow(), 5); boolean b = a >= 120; tabData.setValueAt(b, e.getFirstRow(), 6); } o = tabData.getValueAt(e.getFirstRow(), 0); if (o != null) { //轉換到模型行 int select = e.getFirstRow(); if (select == -1) { return; } select = tabData.getRowSorter().convertRowIndexToModel(select); try { rs.absolute(select 1); //更新資料集中某個位置的內容 rs.updateObject(e.getColumn() 1, tabData.getValueAt(e.getFirstRow(), e.getColumn())); //將內容更新到資料庫 rs.updateRow(); rs.close(); } catch (SQLException ex) { Logger.getLogger(ConnectionSQL.class.getName()).log(Level.SEVERE, null, ex); } } } */ } } |
neoart
版主 發表:22 回覆:582 積分:425 註冊:2003-05-09 發送簡訊給我 |
用jbuilder的話 ,請你自己用F7 / F8 來debug
你的code Lo-Lo-長,我一時之間也沒時間幫你debug 二來我也沒有SQL server,更沒你的資料結構 要怎麼debug ? 很簡單,先從server side,那裡做起,直接把你的server side元件包成可trace的class,先測試直接呼叫這個元件,看他的輸出輸入之後是否正常 再同理測試client caller是否正常可以運作 總之,先把網路摒除之後,問題單純化,比較好下手, 必要時,你的程式要再切成更小的一些片段,比較有利你debug 先找出你有問題的片段,再po上來,這樣是比較負責任的發問,很多問題都是在自己debug時就找到答案了 加油
編輯記錄
neoart 重新編輯於 2008-10-17 00:20:34, 註解 無‧
|
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
|
neoart
版主 發表:22 回覆:582 積分:425 註冊:2003-05-09 發送簡訊給我 |
|
bomaboy
一般會員 發表:3 回覆:9 積分:2 註冊:2008-09-16 發送簡訊給我 |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |