java - JTable 在 JFrame 的(单独的类)JTextfield 中显示选定的行数据

标签 java swing netbeans jframe jtable

我引用了以下链接来寻找解决方案。

Selecting a row from Jtable and get that row data to a another form window in Java

我有两个表,想要在单击表中的记录(在 Course JFrame 中)时将数据插入特定字段(在 Add_lecturer JDialog 中)。

enter image description here

Add_lecturer JFrame我已经尝试过以下方法。

 private void lec_tableMouseClicked(java.awt.event.MouseEvent evt)   {                                       

    int index=lec_table.getSelectedRow();
    TableModel model=lec_table.getModel();
    String lec_code=model.getValueAt(index, 1).toString();

    n.lecid.setText(lec_code);
}                                      

私有(private)类(class)n;在变量声明中。

这是我的Add_lecturer类:

 package SLIOP;

  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import javax.swing.ImageIcon;
  import javax.swing.JOptionPane;
  import javax.swing.table.TableModel;
  import net.proteanit.sql.DbUtils;

public class Add_lecturer extends javax.swing.JDialog {

    Connection conn=null;
    PreparedStatement pst=null;
    ResultSet rs=null;


    public Add_lecturer(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        //SET THE ICON IN TITLE BAR
        this.setIconImage(new ImageIcon(getClass().getResource("Images/logo.png")).getImage());

        try{
        //GET THE CONNECTION TO THE DATABASE 
         conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","");
        }

        catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }

        //SET THE TABLE UPDATE AT THE BEGINNING OF THE INTERFACE
        update_lec_table();     

    }


    private void update_lec_table(){

        try{
           // pst=conn.prepareStatement("select lecturer_code as 'Lecturer ID', course_code as 'Course',sub_type as 'Subject Type' from lecturer ");
           pst=conn.prepareStatement("select student_code,course_code,surname from student_info");
           rs=pst.executeQuery();
            lec_table.setModel(DbUtils.resultSetToTableModel(rs));
        }
        catch(Exception e){
         JOptionPane.showMessageDialog(null,e);
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        lec_table = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Lecturer subject types");

        lec_table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        lec_table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lec_tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lec_table);

        jButton1.setText("Update");

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SLIOP/Images/back.png"))); // NOI18N
        jButton2.setContentAreaFilled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 665, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Course course=new Course();
        course.setVisible(true);

        dispose();
    }                                        

    private void lec_tableMouseClicked(java.awt.event.MouseEvent evt) {                                       

        int index=lec_table.getSelectedRow();
        TableModel model=lec_table.getModel();
        String lec_code=model.getValueAt(index, 1).toString();


        n.lecid.setText(lec_code);
    }                                      

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Add_lecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Add_lecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Add_lecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Add_lecturer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Add_lecturer dialog = new Add_lecturer(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTable lec_table;
    // End of variables declaration                   

    private Course n;
}

有人可以帮我解决这个问题吗?谢谢..

最佳答案

您可以尝试使用 ListSelectionListener 而不是 MouseListener。请看Is it possible jtable row in optionDialog box 。希望您的问题能够得到解决。

第 1 步:请替换以下代码片段:

lec_table.addMouseListener(new java.awt.event.MouseAdapter() {
   public void mouseClicked(java.awt.event.MouseEvent evt) {
     lec_tableMouseClicked(evt);
     }
});

具有以下内容:

lec_table.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {
 @Override
 public void valueChanged(javax.swing.event.ListSelectionEvent event) {
     lec_tableRowSelected(event);               
   }
});

第 2 步:请替换以下代码片段:

 private void lec_tableMouseClicked(java.awt.event.MouseEvent evt) {                                    
    int index=lec_table.getSelectedRow();
    TableModel model=lec_table.getModel();
    String lec_code=model.getValueAt(index, 1).toString();
    n.lecid.setText(lec_code);
 } 

具有以下内容:

private void lec_tableRowSelected(javax.swing.event.ListSelectionEvent event) {                                       
  int index = lec_table.getSelectedRow();
  if (index > -1) {
      TableModel model=lec_table.getModel();
      String lec_code=model.getValueAt(index, 1).toString();
      n.lecid.setText(lec_code);            
     }
 }

第 3 步:请在名为 private void initComponents() 的方法中插入以下行作为第一条语句:

类(class) n=new Course();

关于java - JTable 在 JFrame 的(单独的类)JTextfield 中显示选定的行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38113872/

相关文章:

java - 获取特定 fragment

java - 如何取消 JSlider 的进度指示器与其拇指的链接?

c - ftell 返回不正确的值

java - 如何在空的 iReport 中将 TableModel 设置为 DataSource (NetBeans 7.1)

java - "cannot access java.lang"- Netbeans 6.9.1 中的错误

java xml标签之间的解析

java - 与等效的 Calendar 代码相比,生成的 java.time 代码是否具有更多代码语句

java - 用于 Cognito 的 Java 中的 AWS Lambda 响应

java - 如何在具有撤消功能的缓冲区上绘制?

java - 我正在制作一个简单的计算器,但 GUI 构建一直卡住