2014-12-06 27 views
0

當我執行try和catch函數時,我無法在jframe中添加JPanels我已經嘗試在每次嘗試或catch中添加我的面板,但是它不好請幫助我! ps。它只有當我在嘗試函數之前執行frame.add(new Product("lol"));工作try/catch jdbc java不能把jpanel放在jframe裏面

public static void main(String[] args) { 
     Connection conn = null; 
     Statement stmt = null; 
     frame.setVisible(true); 
     frame.setSize (new Dimension (704, 454)); 
     GridLayout layout = new GridLayout(3, 3, 41, 10); 
     String shit = null; 
     frame.setLayout (layout); 

     try{ 
      //STEP 2: Register JDBC driver 

      Class.forName("com.mysql.jdbc.Driver"); 

      //STEP 3: Open a connection 
      System.out.println("Connecting to a selected database..."); 
      conn = DriverManager.getConnection(DB_URL, USER, PASS); 
      System.out.println("Connected database successfully..."); 


      stmt= conn.createStatement(); 
      ResultSet rs; 

      rs = stmt.executeQuery("select productName from product"); 
      rs.next(); 
      String name = rs.getString("productName"); 
      System.out.println(name); 
      shit = name; 

     }catch(SQLException se){ 
      //Handle errors for JDBC 
      se.printStackTrace(); 
     }catch(Exception e){ 
      //Handle errors for Class.forName 
      e.printStackTrace(); 
     }finally{ 
      //finally block used to close resources 

      try{ 
       if(stmt!=null) 
       conn.close(); 
      }catch(SQLException se){ 
      }// do nothing 
      try{ 
       if(conn!=null) 
       conn.close(); 
      }catch(SQLException se){ 
       se.printStackTrace(); 
      }//end finally try 
     }//end try 
     System.out.println("Goodbye!"); 


     frame.revalidate(); 
     frame.repaint(); 
     frame.add(new Product("lol")); 


    } 
} 

產品類別

public Product(String name){ 
     JLabel label1 = new JLabel(name); 
     add(label1); 
     setBorder(blackline); 

    } 

回答

1

你需要調用repaint()revalidate()添加組件後,所以你應該改變這種代碼

frame.revalidate(); 
frame.repaint(); 
frame.add(new Product("lol")); 

至此

frame.add(new Product("lol")); 
frame.revalidate(); 
frame.repaint(); 
+2

WHOA感謝修復它,我現在感到很蠢:((( – PNC 2014-12-06 07:40:22

+0

)更好的方法是在啓動時在GUI中放置一個空表並在數據庫查詢後填充數據。 – 2014-12-06 07:45:27