java 从 JTable 获取值以设置到 JTextField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13750946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:52:08  来源:igfitidea点击:

Get value from JTable to set into JTextField

javaswingjtablejscrollpanetextfield

提问by newbie

I try to get value from JTableto put into JTextFieldwhen clicking the mouse but it doesn't work. For instance when user selects a row from my table, JTextFieldpopulates with information that is at selected row dynamically.

我试图从获得价值JTable投入JTextField点击鼠标的时候,但它不工作。例如,当用户从我的表JTextField中选择一行时,动态填充所选行的信息。

Also my JTableis in a JScrollPane. Also my table has a DefaultTableModel.

JTable的也在一个JScrollPane. 我的桌子上也有一个DefaultTableModel.

DefaultTableModel model = new DefaultTableModel(){
    public boolean isCellEditable(int row, int column){
        return false;
        }
    };
private JTable jTable1 = new JTable(model);
public Reservation() {
    try {
        jbInit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void jbInit() throws Exception {
    this.getContentPane().setLayout( null );
    this.setSize( new Dimension(400, 300) );
    this.setTitle( "Rezervasyon" );
    jLabel1.setText("Kitap No: ");
    jLabel1.setBounds(new Rectangle(0, 185, 60, 15));
    jTextField1.setBounds(new Rectangle(60, 180, 70, 20));
    jLabel2.setText("Ogrenci No: ");
    jLabel2.setBounds(new Rectangle(165, 180, 65, 20));
    jTextField2.setBounds(new Rectangle(250, 180, 75, 20));
    jButton1.setText("Gonder");
    jButton1.setBounds(new Rectangle(135, 210, 75, 21));
    jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jButton1_actionPerformed(e);
            }
        });
    jLabel3.setText("Ogrenci ID: ");
    jLabel3.setBounds(new Rectangle(5, 30, 100, 15));
    jTextField3.setBounds(new Rectangle(80, 25, 120, 20));
    jScrollPane1.setBounds(new Rectangle(5, 50, 350, 115));
    jScrollPane1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int row = jTable1.getSelectedRow();
                String book = model.getValueAt(row, 0).toString();
                jTextField1.setText(book);
                System.out.println(book);
                String stuID = model.getValueAt(row, 1).toString();
                jTextField2.setText(stuID);
            }
        });
    jButton2.setText("Ara");
    jButton2.setBounds(new Rectangle(285, 25, 75, 21));
    jButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jButton2_actionPerformed(e);
            }
        });
    jScrollPane1.getViewport().add(jTable1, null);
    this.getContentPane().add(jButton2, null);
    this.getContentPane().add(jScrollPane1, null);
    this.getContentPane().add(jTextField3, null);
    this.getContentPane().add(jLabel3, null);
    this.getContentPane().add(jButton1, null);
    this.getContentPane().add(jTextField2, null);
    this.getContentPane().add(jLabel2, null);
    this.getContentPane().add(jTextField1, null);
    this.getContentPane().add(jLabel1, null);
    String header [] ={"Kitap No", "Ogrenci No"};
    for(int i = 0; i < header.length; i++){
        model.addColumn(header[i]);
        }
}

回答by Alex555

I recomend using the TableCellListenerclass. Then you simply go:

我建议使用TableCellListener类。然后你只需去:

//Creating an action for the Listener to use
Action action = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
    //The code to do when the action is performed
    TableCellListener tcl = (TableCellListener)e.getSource();
    <yourTextField>.setText(tcl.getNewValue());
}
};
//Nothing else needed! Listens automatically
TableCellListener tcl = new TableCellListener(table, action);

回答by Amarnath

If you use MouseListenerto perform the task then this code might be helpful. Create a CustomMouseListenerclass and when ever click happens then just call the getSelectedData(..) method such that it will set the value to the JTextField. Setting should be done only from when the mouse is pressed, clickedor entered.

如果您使用MouseListener来执行任务,那么此代码可能会有所帮助。创建一个CustomMouseListener类,当发生单击时,只需调用 getSelectedData(..) 方法,以便将值设置为JTextField. 只应在鼠标处于pressedclicked或 时进行设置entered

class TableMouseListener implements MouseListener {  

   private JTable table; 
   private JTextField textField;   

   public TableMouseListener(JTable table, JTextField textField) {
  this.table = table;
      this.textField = textField;           
   }

 public void mousePressed(MouseEvent e) { 
          getSelectedData(JTable table);
 }  

 public void mouseReleased(MouseEvent e) {}  

 public void mouseEntered(MouseEvent e) {
           getSelectedData(JTable table);
 }  

 public void mouseExited(MouseEvent e) {}  

 public void mouseClicked(MouseEvent e) {
          getSelectedData(JTable table);
 } 

/**
 *  Get the selected row using selectedRow(..) method. Append entire row to the String and set this string to the JTextFIeld.  
*/
public getSelectedData(JTable table) {
        // Get the selected row from the table.
          int selectedRow = table.getSelectedRow();
          String setToTextField = new String();
          for(int i = 0; i < table.getColumnCount(); i++) {
              setToTextField += table.getValueAt(selectedRow, i) + "  ";
          }
          // Finally set this to your JTextField.
         textField.setText(setToTextField);
 }
} 

回答by CodeMan

Probably the easiest way to do this is to use the JTable's MouseClicked Event. Use the following code:

可能最简单的方法是使用 JTable 的 MouseClicked 事件。使用以下代码:

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
    DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel(); //create a model
    int selectedRowIndex = jTable1.getSelectedRow(); //get selected row
    String id = (String) dtm.getValueAt(selectedRowIndex, 0); //get the primary key to fetch data.
    try {
        ResultSet rs = DBCon.getData("Select * from stock where pd_id= '"+id+"'"); //dont worry about dbcon.getdata, its my class to get data.
        while(rs.next()){    //u can use normal query
            pd_id.setText(rs.getString("pd_id"));  //these are my textfields
            pd_name.setText(rs.getString("pd_name"));
            pd_qtys.setText(rs.getString("pd_qtys"));
            pd_qtyw.setText(rs.getString("pd_qtyw"));
            pd_price.setText(rs.getString("pd_price"));
            pd_pkg.setText(rs.getString("pd_pkg"));
        }
    } catch (Exception ex) {
        Logger.getLogger(ExistingStock.class.getName()).log(Level.SEVERE, null, ex);
    }
}

回答by CodeMan

Simply you have to convert model.getValueAt(jTable1.getSelectedRow(),0);to String

只需转换model.getValueAt(jTable1.getSelectedRow(),0);String

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

String textField = (String) model.getValueAt(jTable1.getSelectedRow(),0);  
String textField1 = (String) model.getValueAt(jTable1.getSelectedRow(),1);  

and now just set textFieldand textField1to jTextField1and jTextField2

现在只需设置textFieldtextField1jTextField1jTextField2

jTextField1.setText(textField);
jTextField2.setText(textField1);