繁体   English   中英

从JTable检索数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM