2012-12-04 76 views
1

我試圖在Swing庫接口上包含一個刷新按鈕,該按鈕的用途是在調用添加/刪除/更新查詢後刷新JTable的內容。我已經做了一些研究,看到AbstractTableModel類中的tableDataChanged()。問題是我不知道應該在哪裏調用。我使用的是DefaultTableModel,所以我相信這種方法也可以使用。使用JButton更新JTable

/*This is where I create the query and add the JTable to a scrollPane, an ResultsPanel 
object is then added to a JFrame object*/ 




public class SitePanel extends JPanel implements Constants { 
ResultsPanel resultsPanel = new ResultsPanel(); 
    JTable table; 
    DefaultTableModel model; 
    JPanel sitePanel = new JPanel(); 
    JPanel results = new JPanel(); 

    public SitePanel(){ 
addComponents(); 
} 

public void addComponents(){ 
    sitePanel.setLayout(new BorderLayout()); 
    sitePanel.add(buttonPanel, BorderLayout.NORTH); 
    sitePanel.add(resultsPanel, BorderLayout.CENTER); 
    sitePanel.setVisible(true); 
    add(new JScrollPane(sitePanel)); 
} 

class ButtonPanel extends JPanel{ 
JPanel buttons = new JPanel(); 

     public ButtonPanel(){ 
     buttons.setLayout(new FlowLayout()); 
     buttons.add(refreshButton); 
     show(); 
     buttons.setVisible(true); 
     add(buttons); 

    } 
    public void show(){ 

    refreshButton.addActionListener(new ActionListener(){ 
    @Override 
      public void actionPerformed(ActionEvent arg0) { 
       new ResultsPanel(); 
       table.setModel(model); 
      } 
     } 
       ); 
} 
public class ResultsPanel extends JPanel{ 


    public ResultsPanel(){ 

     execute(); 
     results.add(scrollPane); 
     javax.swing.SwingUtilities.invokeLater(new Runnable(){ 
      public void run(){ 
       results.setBorder(greenB); 
       results.setToolTipText("Results"); 
       results.setVisible(true); 
       add(results); 

      } 
     }); 
    } 

     public void execute() { 
     Vector columnNames = new Vector(); 
     Vector data = new Vector(); 

     try{ 
      Connection conn = Connect.getConnection(); 
      String query = "Select Name from Location Order By Name"; 
      Statement stmt = conn.createStatement(); 
      ResultSet rs = stmt.executeQuery(query); 
      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(); 
      conn.close(); 
     } 
     catch (Exception e){ 
      e.printStackTrace(); 
     } 
     model = new DefaultTableModel(data, columnNames); 

     model.addTableModelListener(table); 
     table = new JTable(model){ 
      public boolean isCellEditable(int row, int col){ 
       return false; 
      } 

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

     scrollPane = new JScrollPane(table); 
     scrollPane.setBorder(border); 
     scrollPane.getVerticalScrollBar().setBackground(Color.LIGHT_GRAY); 
    } 
} 

      } 

這是主要方法的類。

import java.net.URL; 
import java.sql.*; 
import javax.swing.*; 



public class Connect extends JFrame{ 

public static String user = null; 
public static String password = null; 
static Connection conn = null; 

public static void loginGUI() throws Exception{ 
    JPasswordField passwordField = new JPasswordField(); 
    JTextField userField = new JTextField(); 
    passwordField.setEchoChar('*'); 
    Object[] obj = {"Username:\n", userField, "Password:\n", passwordField}; 
    Object stringArray[] = {"OK", "Cancel"}; 
    if(JOptionPane.showOptionDialog(null, obj, "Login", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj)==JOptionPane.YES_OPTION); 
    password = new String (passwordField.getPassword()); 
    user = userField.getText(); 
    Conn.formConnection(); 


} 



public static void main (String[] args) throws Exception{ 
      javax.swing.SwingUtilities.invokeLater(new Runnable(){ 
     public void run(){ 
      try { 
            Connect.loginGUI(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 
/** 
* Static connection class can only be created once at any given time. 
* @author Nosheen Mahate 
* 
*/ 
public static class Conn{ 

    public static Connection formConnection() throws Exception{ 
     try{ 
      String driver = "net.sourceforge.jtds.jdbc.Driver"; 
      String url = "jdbc:jtds:sqlserver://BHX4DT-4FPQ35J:1433/Forecast;instance=SQLEXPRESS" + 
        ";user=" +user +";password="+ password +";ssl=request;Encrypt=true;TrustServerCertificate=true"; 
      Class.forName(driver); 
      conn = DriverManager.getConnection(url, user, password); 

      try{ 
       password = null; 
       JFrame frame = new JFrame(); 
               frame.add(new SitePanel()); 
               frame.pack(); 
               frame.setVisible(true); 
      } 
      catch (Exception e){ 
       System.exit(1); 
       JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE); 


       e.printStackTrace(); 

      } 
     } 
     catch (Exception e){ 
      if(password != null || user !=null){ 
       JOptionPane.showMessageDialog(null, e, "Error",  JOptionPane.ERROR_MESSAGE); 
      } 
      else{ 
      System.exit(1); 

      } 
      System.out.println("No Connection"); 
     } 

     return conn; 

    } 
    /** 
    * Used to check that the connection is still established 
    */ 
} 
public static Connection getConnection(){ 
    return conn; 
} 

/** 
* Close the connection to the server 
* @throws SQLException 
*/ 
public static void closeConnection() throws SQLException{ 
    conn.close(); 
    conn = null; 
} 
} 

我知道有相當多的代碼有,但我也不太清楚,你可能需要的東西。 爲了重新運行,我想知道如何在點擊JButton後更新JTable,以及如何調用fireTableDataChanged()方法(如果需要)。

+1

*「我知道這裏有相當多的代碼,但我不太清楚你可能需要什麼。」*這不是'相當多'IMO。我希望人們可能會看到(或至少編譯)更多的LOC,如果不是2個片段,你會發佈一個[SSCCE](http://sscce.org/)。 –

+0

@AndrewThompson認爲更清楚,謝謝你的提示。 – Nosheen

+1

良好的編輯,但請注意SSCCE需要一個'main(String [])'把它扔在屏幕上,就像這個[小例子](http://stackoverflow.com/a/8958814/418556) 。 –

回答

2
  1. 請讓一下,與

  2. 開始嘗試避免同時更新(AM)XxxResultSetTableModelEventDispatchThread

  3. Workers Thread開頭的所有JDBCJTable小號更新,從Runnable#Thread,從SwingWorke [R越好,否則Swing GUI的會凍結,直到JDBCJTables更新結束

  4. 通知,無論代碼是代碼示例,有以移動所有Xxx.close()到(添加創建一個新的)finally塊(try - catch - finally

+0

謝謝,我需要閱讀您發佈的這些鏈接。你是否指出我的表沒有得到更新的原因是因爲線程是如何使用的,或者這會更好地代表它運行時的代碼嗎? – Nosheen

+0

以及mKorbel發佈的內容,我發現[這篇文章](http://today.java.net/pub/a/today/2003/10/24/swing.html)也很有幫助。 – Nosheen