2016-10-05 77 views
0

以及我使這個系統有一個表,我必須把按鈕放在最後一列。我一直在研究,但我看到的所有代碼都很混亂。有一個壽,但仍然有一些我不明白的部分。這裏的地方我知道了http://www.javaquery.com/2013/05/how-to-implement-jbutton-in-jtable.html更簡單的方法來添加jbutton jtable

String[] InvoiceArray = new String[20]; 
//Declare above variable globally. Used by two-three methods. Change variable name as per your need. 

/* 
* import the ButtonColumn class if you are not working in IDE 
* I used formWindowOpened event to load content in Jtable but you can use other event. 
* All you need is put the code with in that event. 
*/ 
private void formWindowOpened(java.awt.event.WindowEvent evt) { 
     Object[][] rowData = new Object[4][2]; // 4: is number of row ; 2: is number of column 
     Object columnNames[] = {"Invoice No", "View Report"}; // Name of columns 
     for (int i = 0; i < 4; i++) { 
      InvoiceArray[i] = i + "-2345"; 
      rowData[i][0] = i + "-2345"; 
      rowData[i][1] = "View Order " + i; // Can change the text of button. 
     } 
     DefaultTableModel tm = new DefaultTableModel(rowData, columnNames); 
     jTable1.setModel(tm); 
     ButtonColumn buttonColumn = new ButtonColumn(jTable1, showOrder, 1); // 1: is column number. column count starts with 0,1,2... 
} 

有什麼InvoiceArray的網站?我應該從最後一行開始showOrder?另外,我不明白他發佈的關於如何讓聽衆進行發佈的代碼。這裏是:

Action showOrder = new AbstractAction() { 
     public void actionPerformed(ActionEvent e) { 
     //JTable table = (JTable) e.getSource(); // If you have multiple component following the ActionEvent 
      int modelRow = Integer.valueOf(e.getActionCommand()); 
      if (InvoiceArray[modelRow] != null) { 
       /* We are placing invoice no in array 
       * And track the button click index 
       * And fetch index in invoice no 
       */ 
       System.out.println("Your Invoice No:" + InvoiceArray[modelRow]); 
      } else { 
       JOptionPane.showMessageDialog(rootPane, "No records found!"); 
      } 
     } 
}; 

我知道已經有一些解釋。我瞭解其中的一些,但不是全部。只是在jtable上添加jbutton以及爲jbutton添加jitter的簡單方法。非常感謝你

回答

2

只是一個簡單的方法來添加jbutton jtable和jbutton聽衆。

沒有簡單的方法。您需要了解呈現器和編輯器如何在JTable中工作。有關基礎知識,請參閱Concepts: Renderers and Editors的Swing教程中的部分。

然後你可以看看Table Button Column這對你來說很辛苦。你只需要提供Action當你點擊按鈕時被調用。

什麼是InvoiceArray?

它用於將數據加載到JTable中。這是一個JTable的基本用法,並且與向該表的一列添加按鈕完全無關。

數據加載後,您應該忘記invoiceArray。您編寫的操作應通過TableModel或JTable訪問數據。

+0

你可以給我一個非常非常短的代碼如何做到這一點嗎?我已經檢查過表格按鈕列,仍然很混亂,我不明白他在哪裏添加了助記符:/ – luh

+0

@luh,你被給了簡單的代碼。您創建一個JTable並向其添加數據。這是標準的JTable處理。該發佈假定您知道如何使用數據創建JTable並將該表添加到框架。如果你不知道如何做到這一點,那麼請閱讀教程中的工作示例。然後有7行代碼顯示如何添加一個Action來刪除被點擊的行。 「我不明白他在哪裏添加助記符 - - 什麼?你有沒有看到「setMnemonic(...)」語句?我不明白你的困惑。 – camickr

+0

哦,我的意思是他爲什麼添加助記符?爲什麼他還說助記符只是可選的。如果我把它拿出來,我會改變他的代碼中的任何東西嗎?是的,我知道如何創建Jtable的數據,我真的不知道如何添加jbuttons與聽衆。並從示例代碼中,如果'InvoiceArray'不是那麼重要,我可以把它關掉嗎? showOrder是什麼? – luh