0

在我的以下代码中,我可以通过单击“添加”和搜索按钮成功地在表格中显示数据。但是在单击“获取值”后,它没有显示“jtable2”,它被给出为“jTable2.setModel(new DefaultTableModel(data3,columns2));” 这里有两个 Jtable。点击“Get Values”后分配Jtable2 代码为:

     package com.ash;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JLabel;
    import javax.swing.GroupLayout.Alignment;
    import javax.swing.GroupLayout;
    import javax.swing.LayoutStyle.ComponentPlacement;
    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JPanel;


    public class ReportD extends javax.swing.JFrame {
 static Object[][] data ;
 static Object[][] data2;
static Object[] columns={"FirstName","LastName","Age","RefDoctor","Sex","RegId","test"};

public static int NumOfCol;
public Object[] columns2;
static Object[][] data3;

    Connection con;
    Connection con2,con3;
    ResultSet rs,rs1,rs2,rs3;


Statement stmt=null;
Statement stmt2=null;
Statement stmt3=null;
int k=0;
PreparedStatement pr,pr2,pr3;
String Gid,Gtest;

public ReportD() {
    initComponents();
}


private void initComponents() {



    jButton1 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jTextField1 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();


    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Report");
   //jtable1



    jButton1.setText("Add");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            try {
                jButton1ActionPerformed(evt);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    table.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null, null, null,null},

        },
        new String [] {
            "First Name", "Last Name", "Age", "Ref Doctor", "Sex", "Reg Id","test"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false, false, false,false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jScrollPane1.setViewportView(table);
    table.getColumnModel().getColumn(0).setResizable(false);
    table.getColumnModel().getColumn(1).setResizable(false);
    table.getColumnModel().getColumn(2).setResizable(false);
    table.getColumnModel().getColumn(3).setResizable(false);
    table.getColumnModel().getColumn(4).setResizable(false);
    table.getColumnModel().getColumn(5).setResizable(false);
    table.getColumnModel().getColumn(6).setResizable(false);

    jButton2.setText("Search");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt1) {

                try {
                    jButton2ActionPerformed(evt1);
                } catch (ClassNotFoundException | SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } //catch block created 

        }
    });

    jLabel1.setText("Enter Reg. Id");

    // The button Get Value and it prints the value of selected row 
    getValue = new JButton("Get Value");
    getValue.setToolTipText("Get values from table");
    getValue.addActionListener(new ActionListener() {
        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent e) {



                      Gid = (String) table.getValueAt(table.getSelectedRow(), 5);  
                      Gtest=(String) table.getValueAt(table.getSelectedRow(), 6);
                      System.out.println(Gid);
                      System.out.println(Gtest);





                        //selected's code start here yo yoooo
                      jScrollPane2 = new javax.swing.JScrollPane();
                    jTable2 = new javax.swing.JTable();

                      //storing the value of Registration id and test did from the ReportD table
                    try {
                      System.out.println("in selected"+Gid+Gtest);
                      con=DbConnPa.getConObj();
                      con3=DbConnPa.getConObj();

                      Statement st = con.createStatement();
                      ResultSet rs = st.executeQuery("SELECT * FROM "+Gtest+"");
                      ResultSetMetaData rsmd = rs.getMetaData();
                     NumOfCol = rsmd.getColumnCount();   //it stores the number of columns in NumOfCol
        //            System.out.println("No. of columns in "+Gtest+"is"+NumOfCol);
                      String o1="null";
                      String t1="\"Title";
                      String c1="\"";
                      String c2=c1.concat(rsmd.getColumnName(1)+"\"");
                      int m=1;
                      for(m=1;m<NumOfCol;m++){
                        o1=o1.concat(",null");
                        t1=(t1+m).concat("\",\"Title");
                        }System.out.println(o1);
                      System.out.println(t1+(m)+"\"");

                      for(int n=2;n<=NumOfCol;n++)
                      {
                      //System.out.println("Name of ["+i+"] Column="+rsmd.getColumnName(i));
                      c2=c2.concat(","+"\""+rsmd.getColumnName(n)+"\"");
                      }System.out.println(c2);




                    jTable2.setModel(new javax.swing.table.DefaultTableModel(
                          new Object [][] {{o1},}, new String [] {c2}   ));

                  //  Object columns2[]={c2};
                        String sql3="SELECT COUNT (*) FROM "+Gtest+" where regid LIKE '"+Gid+"%'";
                        pr3=con3.prepareStatement(sql3);
                        rs3=pr3.executeQuery(sql3);
                        rs3.next();

                        int count = 0;
                    //  int col1=NumOfCol;

                        count = rs3.getInt(1);
                            System.out.println(count);
                            data3= new Object [count][NumOfCol];
                        stmt3=con3.createStatement();

                        String sql4="SELECT * FROM "+Gtest+" where regid LIKE '"+Gid+"%'";
                        rs3=stmt3.executeQuery(sql4);
                            k=0;
                        while(rs3.next()){
                                for(int j=0;j<NumOfCol;j++){
                                        data3[k][j]=rs3.getString(j+1);
                                System.out.println("k:"+k+"j:"+j);
                                }
                            k++;}




                      Object[] columns2={c2};

                    jScrollPane2.setSize(745, 134);
                    jScrollPane2.setLocation(0, 570);
                        jTable2.setColumnSelectionAllowed(true);
                    jScrollPane2.setViewportView(jTable2);
                    jTable2.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
                        jTable2.setModel(new DefaultTableModel(data3, columns2));
                        jTable2.setVisible(true);

                        } catch (ClassNotFoundException e1) {
                        e1.printStackTrace();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
        }
    });



    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    layout.setHorizontalGroup(
        layout.createParallelGroup(Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(69, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(getValue)
                        .addGap(431))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(Alignment.LEADING)
                            .addComponent(jButton1)
                            .addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(10)
                                    .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(ComponentPlacement.RELATED)
                                    .addComponent(jTextField1)
                                    .addPreferredGap(ComponentPlacement.UNRELATED)
                                    .addComponent(jButton2))
                                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 536, GroupLayout.PREFERRED_SIZE)))
                        .addGap(224))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(30)
                .addComponent(jButton1)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(Alignment.LEADING, false)
                    .addGroup(layout.createParallelGroup(Alignment.BASELINE)
                        .addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(5)))
                .addGap(2)
                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 184, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(ComponentPlacement.RELATED)
                .addComponent(getValue)
                .addContainerGap(371, Short.MAX_VALUE))
    );
    getContentPane().setLayout(layout);


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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) throws ClassNotFoundException, SQLException {                                         

            con=DbConnPa.getConObj();
            String sql="SELECT COUNT (*) FROM newpatient1";
            pr=con.prepareStatement(sql);
            rs=pr.executeQuery(sql);
            rs.next();

            int count = 0;
            count = rs.getInt(1);
            System.out.println(count);

            data= new Object [count][7];
            stmt=con.createStatement();
            String sql1="SELECT * FROM newpatient1";

            rs1=stmt.executeQuery(sql1);
                    while(rs1.next()){
                        for(int j=0;j<7;j++){
                                data[k][j]=rs1.getString(j+1);
                            //  System.out.println("i="+"j="+j);
                        }
                k++;}
            table.setModel(new DefaultTableModel(data, columns));
            table.setAutoCreateRowSorter(true);
   }                                        

public void jButton2ActionPerformed(java.awt.event.ActionEvent evt1) throws SQLException, ClassNotFoundException {                                         

String search=jTextField1.getText();
con2=DbConnPa.getConObj();

           String sql="SELECT COUNT (*) FROM newpatient1 where regid LIKE '"+search+"%'";
           pr=con2.prepareStatement(sql);
           rs=pr.executeQuery(sql);
           rs.next();
           int count = 0;

           count = rs.getInt(1);
           System.out.println(count);


           data2= new Object [count][7];
           stmt=con2.createStatement();                     

            //String sql2="SELECT * FROM newpatient1 WHERE regid LIKE"+"'"+search+"%'";

           String sql2="SELECT * FROM newpatient1 where regid LIKE '"+search+"%'";
            System.out.println(search);

            stmt2=con2.createStatement();
            rs2=stmt2.executeQuery(sql2);
            k=0;
                    while(rs2.next()){
                        data2[k][0]=rs2.getString(1);
                        data2[k][1]=rs2.getString(2);
                        data2[k][2]=rs2.getString(3);
                        data2[k][3]=rs2.getString(4);
                        data2[k][4]=rs2.getString(5);
                        data2[k][5]=rs2.getString(6);
                        data2[k][6]=rs2.getString(7);

                        String data=rs2.getString(2);
                    //  System.out.println(data+"k=="+k);
                    k++;}
                    table.setModel(new DefaultTableModel(data2, columns));
        }                                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ReportD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ReportD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ReportD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ReportD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ReportD().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTable table;
private javax.swing.JTable jTable2;
private JButton getValue;
    }
4

1 回答 1

1

您正在设置视口,jScrollPane2但是jTable2,您并没有添加jScrollPane2到它JFrame本身。在我看来,actionPerformedgetValue JButton应该写:

jScrollPane1.setViewportView(jTable2);

代替

jScrollPane2.setViewportView(jTable2);

编辑
如果您不想替换视jScrollPane1口,则只需jScrollPane2JFrame. 它会显示jTable2在您的JFrame.

于 2013-04-28T14:56:31.990 回答