2016-05-15 4 views
0

JTable(この場合はt1)を使用してListSelectionListenerを実装する小さなプログラムを作成するので、その行のデータをデータベースに格納します(mysqlとJDBCを介して接続します)。getValueAt()はデータベースへのエントリを2倍にしました

// t1 is a JTable 
t1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
t1.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 

    @Override 
    public void valueChanged(ListSelectionEvent e) { 

      int row = t1.getSelectedRow(); 

      try { 
       String sql = "INSERT INTO xxx (x1, x2, x3) VALUES(?,?,?)"; 

       PreparedStatement pst = conn.prepareStatement(sql); 

       int col1 = (int)t1.getValueAt(row, 0); 
       int col2 = (int)t1.getValueAt(row, 1); 
       int col3 = (int)t1.getValueAt(row, 2); 

       pst.setLong(1, col1); 
       pst.setLong(2, col2); 
       pst.setLong(3, col3); 

       pst.addBatch(); 

       pst.executeBatch(); 
     } 

      catch (SQLException e1) { 

      e1.printStackTrace(); 
     } 
    } 
}); 

各行がデータベースに2回置かれている点を除いて、すべて正常に動作します。たとえば、3行目を選択すると、データベースで2回取得されます。マウスを押したときに1つのエントリを作成し、リリースするときに1つのエントリを作成するように見えます。キーボードの矢印を使用すると表示されません。誰でも助けてくれますか?

答えて

1

以下のロジック

ListSelectionModel selectionModel = table.getSelectionModel(); 
    selectionModel.addListSelectionListener(new ListSelectionListener() { 
     public void valueChanged(ListSelectionEvent e) { 
      if (e.getValueIsAdjusting()){ 
       return; 
      } 
      if (e.getSource() == table.getSelectionModel() && 
       table.getRowSelectionAllowed()) { 
       int selected = table.getSelectedRow(); 
       System.out.println("Column 1 : " + table.getValueAt(selected, 0)); 
       System.out.println("Column 2 : " + table.getValueAt(selected, 1)); 
       System.out.println("Column 3 : " + table.getValueAt(selected, 2)); 
      } 
     } 
    }); 

を使用してください、私はこの記事を見java-listselectionlistener-interface-with-keyboard

関連する問題