2014-02-09 33 views
0

我有JTable,列名爲" Names "," Quantity "" Unit "。 我正在編寫一個程序,您可以獲得配料名稱。 所以我需要得到一列的整個行,並把它們串起來, ,因爲我需要將它存儲在mySql中,我已經將它全部設置爲String。 任何想法我可以做到這一點? 我的代碼如下:從JTable的第一列獲取一行名稱

的JTable代碼:

DefaultTableModel model = (DefaultTableModel)table.getModel(); 
if(!txtQty.getText().trim().equals("")){ 

    model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()}); 
}else{ 

    JOptionPane.showMessageDialog(null,"*Quantity field left blank"); 
} 

獲取值和存儲:

for(int i = 1; i<= i ; i++){ 
    ingredients = table.getName(); 
} 

這是循環是錯誤的,這是行不通的,因爲我有一個構造函數採取配料,但因爲它在循環內,它不能把它。 任何建議請?謝謝。

構造:

Food e2 = new Food(Name, Description, priceDbl, Image, Category, Ingredients, promotion); 

e2.createFood(); 

回答

1

我編碼你在哪裏得到的成分名稱的程序。所以我需要把整行的一列和字符串放在一起,因爲我需要將它存儲在mySql中,並且我已經將它全部設置爲String。

想要這樣做,試試這個。在這裏,我得到的結果爲ArrayListString,因爲我評論ArrayList可以避免它。

public class TableValuePrint extends JFrame implements ActionListener{ 
    private final JButton print; 
    private final JTable table; 
    private String str=""; 

    public TableValuePrint() { 
     setSize(600, 300); 
     String[] columnNames = {"A", "B", "C"}; 
     Object[][] data = { 
      {"Moni", "adsad", "Pass"}, 
      {"Jhon", "ewrewr", "Fail"}, 
      {"Max", "zxczxc", "Pass"} 
     }; 

     table = new JTable(data, columnNames); 
     JScrollPane tableSP = new JScrollPane(table); 
     JPanel tablePanel = new JPanel(); 
     tablePanel.add(tableSP); 
     tablePanel.setBackground(Color.red); 
     add(tablePanel); 
     setTitle("Result"); 

     setSize(1000,700); 

     print=new JButton("Print"); 
     JPanel jpi1 = new JPanel(); 
     jpi1.add(print); 
     tablePanel.add(jpi1,BorderLayout.SOUTH);  

     print.addActionListener(this); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      public void run() { 
       TableValuePrint ex = new TableValuePrint(); 
       ex.setVisible(true); 
      } 
     }); 
    } 

    @Override 
    public void actionPerformed(ActionEvent ae) { 
     if(ae.getSource()==print){ 
//   ArrayList list = new ArrayList(); 
for(int i = 0;i<table.getModel().getRowCount();i++) 
{ 
//list.add(table.getModel().getValueAt(i, 0)); //get the all row values at column index 1 
str=str+table.getModel().getValueAt(i,0).toString(); 
} 
//System.out.println("List="+list); 
System.out.println("String="+str); 
     } 
    } 
} 

輸出 output

字符串= MoniJhonMax