2014-06-06 97 views
-1

我有一個框架與表,組合框,我想通過組合框填充表中的數據從數據庫,但如果我用itemlistener我沒有看到表,沒有itemlistener和String sql="select * from Arlista"然後我用數據看到我的表格。 (combob =組合框)我沒有看到我的表

編輯:現在我得到的錯誤爲主體,「修改‘靜態’只允許在不斷的變量聲明

public static class TableFromDatabase extends JFrame 
{   Vector columnNames = new Vector(); 
      Vector data = new Vector(); 
      String [] asd={"Arlista"}; 
      JComboBox combob=new JComboBox(asd); 

      String tesztvalt2; 
    public TableFromDatabase() { 

     combob.addItemListener(new ItemListener(){ 
      @Override 
      public void itemStateChanged(ItemEvent e){ 
       tesztvalt2=(combob.getSelectedItem()).toString(); 
     if (e.getItem().equals(tesztvalt2)) { 
       try { 

      String url="jdbc:sqlserver://FARKAS-PC;databaseName=Mozi;integratedSecurity=true;"; 
      String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
      Class.forName(driver); 
      Connection connection = DriverManager.getConnection(url); 

      String sql = "Select * from "+tesztvalt2+""; 
      Statement stmt = connection.createStatement(); 
      ResultSet rs = stmt.executeQuery(sql); 
      ResultSetMetaData md = rs.getMetaData(); 
      int columns = md.getColumnCount(); 

      for (int i = 1; i <= columns; i++) 
      { 
       columnNames.addElement(md.getColumnName(i)); 
      } 


      while (rs.next()) { 
       Vector row = new Vector(columns); 

       for (int i = 1; i <= columns; i++) 
       { 
        row.addElement(rs.getObject(i)); 
       } 

       data.addElement(row); 
      } 

      rs.close(); 
      stmt.close(); 
      connection.close(); 
     } 
     catch(Exception ex) 
     { 
      System.out.println(ex); 
     } 


     JTable table = new JTable(data, columnNames) 
     { 
      public Class getColumnClass(int column) 
      { 
       for (int row = 0; row < getRowCount(); row++) 
       { 
        Object o = getValueAt(row, column); 

        if (o != null) 
        { 
         return o.getClass(); 
        } 
       } 

       return Object.class; 
      } 
     }; 

     JScrollPane scrollPane = new JScrollPane(table); 
     getContentPane().add(scrollPane); 

     JPanel buttonPanel = new JPanel(); 
     getContentPane().add(buttonPanel, BorderLayout.SOUTH); 
     JPanel panel = (JPanel)getContentPane(); 
     panel.add(buttonPanel, BorderLayout.SOUTH); 
     panel.revalidate(); 
     panel.repaint(); 
    } 
      } 


    public static void main(String[] args) 
    { 
     TableFromDatabase frame = new TableFromDatabase(); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     frame.pack(); 
    } 
     }); 
       }   
     } 

回答

1

Table From Database複製的代碼只是設計來展示如何調用SQL並創建JTable並將其添加到框架的基礎知識,這意味着該代碼中的pack()方法將調用佈局管理器,以便新創建的表具有有效大小。

您正試圖在可見的GUI上動態創建一個JTable。所以你不能只添加表格/滾動條到框架。您還需要重新驗證()所有組件。基本代碼是:

JPanel panel = (JPanel)getContentPane(); 
panel.add(buttonPanel, BorderLayout.SOUTH); 
panel.revalidate(); 
panel.repaint();