[英]Data retrieving from JTable
我正在嘗試從Java表中獲取數據。 我已經能夠獲取數據,但是在輸出數據時,它是自己連接的。 如果數據為“ admin”,則輸出為“ adminadmin”。 下面是代碼。 有人可以告訴我問題是什么嗎?
package sample;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.sql.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.proteanit.sql.DbUtils;
public class Table extends JFrame{
JTable table;
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private int row;
private String name, status;
private void connect(){
conn = myconnection.ConnectDb();
}
public void mouseClicked(MouseEvent e) {
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int sel = table.getSelectedRow();
name = table.getModel().getValueAt(sel, 0).toString();
System.out.print(name);
}
});
}
private void UpdateJTable(){
String sql = "select firstname, status from tblmember";
try{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
public Table(){
setLayout(new FlowLayout());
String [] columnName={"Name", "Status"};
Object [][] data={
{null, null},
{null, null}
};
table = new JTable(data, columnName);
table.setPreferredScrollableViewportSize(new Dimension(400,50));
table.setFillsViewportHeight(true);
JScrollPane sp = new JScrollPane(table);
add(sp);
}
public static void main(String[] args){
Table gui = new Table();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(700, 500);
gui.setVisible(true);
gui.setTitle("AAAAAAAA");
gui.connect();
gui.UpdateJTable();
gui.mouseClicked(null);
}
}
由於選擇事件被觸發兩次,所以您將其串聯起來,並使用System.out.print()
顯示選擇。
如果事件的getValueIsAdjusting()
方法返回true,則應該忽略該事件。
另外,請注意返回的選定行索引不一定與表模型索引相同:如果對表進行排序,則兩個索引將不同。 從模型獲取數據之前,請使用JTable的convertRowIndexToModel()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.