我想创建一个JTable,"分析","日期"和"价格"列的名称。 Analysis和Price的值从我的数据库中的数据库中恢复,Date得到当天的值。
我创建了一个MyModel类,如下所示:
package com.pack.classes;
import java.util.LinkedList;
import javax.swing.table.AbstractTableModel;
import com.pack.beans.MyElement;
@SuppressWarnings("serial")
public class MyModel extends AbstractTableModel {
public static final String[] columnNames = {"Analyse", "Date d'analyse","Prix"};
private final LinkedList<MyElement> list;
public MyModel() {
list = new LinkedList<MyElement>();
}
public void addElement(MyElement e) {
// Adds the element in the last position in the list
list.add(e);
fireTableRowsInserted(list.size()-1, list.size()-1);
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0: return list.get(rowIndex).getAnalysis();
case 1: return list.get(rowIndex).getDate();
case 2: return list.get(rowIndex).getPrice();
}
return null;
}
}
我创建了一个Bean MyElement,如下所示:
package com.pack.beans;
import java.util.Date;
public class MyElement {
String analysis;
Date date;
Double price;
public String getAnalysis() {
return analysis;
}
public void setAnalysis(String analysis) {
this.analysis = analysis;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
以下是我使用此类的代码:
String sql = "Select name,number_b from analysis_tab where name ='" + idclicked + "'";
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
System.out.println(dateFormat.format(date));
PreparedStatement preparestate = database.con.prepareStatement(sql);
ResultSet rs = preparestate.executeQuery();
MyModel mymodel = new MyModel();
String [] value = mymodel.columnNames;
MyElement e = new MyElement();
//e.setAnalysis(name);
e.setDate(date);
//e.setPrice("number_b");
结果我获得了一张表格,其中包括3个&#34; A&#34;,&#34; B&#34;和&#34; C&#34;。我不知道因此这些名字来了!!! 你应该告诉我如何把我的专栏名称和#34;分析&#34;,&#34;日期d&#39;分析&#34;,&#34; Prix&#34;作为我表中的标题?我是否在正确的道路上?
答案 0 :(得分:1)
为什么不使用DefaultTableModel? 它比仅使用jtable强大。
//插入列名
defaultTableModel.setColumnIdentifiers(new String[]{"Analyse", "Date d'analyse","Prix"});
而且..你的sql是声明类型!如果可以,请更改下面的sql样式。
String sql = "Select name,number_b from analysis_tab where name ='" + idclicked + "'";
<强> =&GT; 强>
String sql = "Select name,number_b from analysis_tab where name = ?"
PreparedStatement preparestate = database.con.prepareStatement(sql);
pstmt.setString(1, idclicked);
rs = pstmt.executeQuery();
检查&#34; PreparedStatement&#34;和#34;陈述&#34;! :)