Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JButton更新JTable_Java_Swing_Jdbc_Jtable_Jbutton - Fatal编程技术网

Java 使用JButton更新JTable

Java 使用JButton更新JTable,java,swing,jdbc,jtable,jbutton,Java,Swing,Jdbc,Jtable,Jbutton,我试图在Swing库界面上包含一个刷新按钮,该按钮的目的是在调用添加/删除/更新查询后刷新JTable的内容。我做了一些研究,发现tableDataChanged()来自AbstractTableModel类。问题是我不确定这个应该叫什么名字。我使用的是DefaultTableModel,所以我相信这个方法也可以使用 /*This is where I create the query and add the JTable to a scrollPane, an ResultsPanel ob

我试图在Swing库界面上包含一个刷新按钮,该按钮的目的是在调用添加/删除/更新查询后刷新
JTable
的内容。我做了一些研究,发现
tableDataChanged()
来自
AbstractTableModel
类。问题是我不确定这个应该叫什么名字。我使用的是
DefaultTableModel
,所以我相信这个方法也可以使用

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

           }
我知道那里有很多代码,但我不太确定您可能需要什么。 为了重新运行,我想知道单击
JButton
后如何更新
JTable
,以及调用
fireTableDataChanged()
方法的位置(如果需要)

  • 请看一下,从

  • 要避免在上同时更新(上午)
    xxxresultsetablemodel

  • Workers线程
    、从
    Runnable#线程
    启动所有
    JDBC
    JTable的更新,最好从
    SwingWorke
    r启动,否则SwingGUI将被冻结,直到
    JDBC
    JTables
    更新结束

  • 注意,这两个代码都是代码示例,必须移动所有
    Xxx。关闭(
    )到(添加创建新的)
    最终
    块(
    try
    -
    catch
    -
    最终


  • “我知道那里有相当多的代码,但我不太确定您可能需要什么。”在我看来,这不是“相当多”。我希望如果您发布一个代码段而不是两个代码段,人们可能会看到(或至少编译)更多的代码段。@AndrewThompson认为这更清楚,感谢您的提示。编辑得好,但请注意SSCE需要
    main(String[])
    将其扔到屏幕上,如下所示。很抱歉,我忘记将其包含在另一个类中。SSCCE中可能有多个类。谢谢,我需要仔细阅读你发布的这些链接。你是在指出我的表没有得到更新的原因是因为线程的使用方式,还是这会让我的代码在运行时变得更好?以及mKorbel发布的内容,我发现也很有帮助。
    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;
    }
    }