【问题标题】:JTable show selected row data in a JFrame's (separate class) JTextfieldJTable 在 JFrame 的(单独的类)JTextfield 中显示选定的行数据
【发布时间】:2016-06-30 04:12:02
【问题描述】:

我参考了以下链接以找到解决方案。

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

我有两个表,想在单击表中的记录(Add_lecturerJDialog)时将数据插入特定字段(CourseJFrame)。

Add_lecturerJFrame我已经尝试了以下。

 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);
}                                      

私人课程 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;
}

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

【问题讨论】:

  • 你能分享Add_lecturer.java吗?
  • 我已经添加了 Add_lecturer.java。我需要知道我的代码中的错误在哪里。
  • 如需尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example
  • 您声明并使用变量private Course n;。看起来,这个变量没有被初始化,所以这可能是原因,因为你得到了一个NullPointerException。欲了解更多信息,请查看here

标签: java swing netbeans jframe jtable


【解决方案1】:

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

第 1 步:请替换您的代码的以下 sn-p:

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 步:请替换以下代码的 sn-p:

 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() 的方法中插入以下行作为第一条语句:

Course n=new Course();

【讨论】:

  • 嗨@lakshi,你能看看编辑过的答案,告诉我它是否有效吗?
  • 仍然会弹出错误。删除 mouseclick 事件后,步骤 1 代码现在不存在。你能告诉我修复它的路径吗?
  • 嗨@lakshi 你能分享所有其他相关的Java 文件吗?
  • @SanjeevSaha 看起来,作者不明白他(她)使用的所有变量都必须初始化(参见我对原帖的评论)。
  • 我无法上传整个代码。还有其他选择吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
  • 2012-10-04
相关资源
最近更新 更多