TableModel,导致 Java JFrame 中出现重复的数据库信息

Posted

技术标签:

【中文标题】TableModel,导致 Java JFrame 中出现重复的数据库信息【英文标题】:TableModel, causing duplicate Database Info in a Java JFrame 【发布时间】:2013-03-15 16:22:37 【问题描述】:

当用户按下按钮“加载文件”时,我在 JFrame 中设置了这个方法;但是,当用户第二次按下按钮时。 . .他们在第一个表格下方获得了另一个表格,因此所有信息都被复制,并且超出了我的“不可调整大小”框架。

无论用户按下多少次按钮,我怎样才能让它只加载一个表?

    JButton btnLoad = new JButton("Load File")

private void GetAction()

    ActionHandler handler = new ActionHandler();
    btnLoad.addActionListener(handler);


    private class ActionHandler implements ActionListener
       
    public void actionPerformed(ActionEvent evt) 
    
        String incmd = evt.getActionCommand();
        if (incmd.equals("Load File")) // If Load File button is pressed
            DatabaseLoad();
        else if (incmd.equals("Exit")) // If Exit button is pressed
            System.exit(0);  
    

    private void DatabaseLoad()
    
        try 
        
            // The driver allows you to query the database with Java
            // forName dynamically loads the class for you           
            Class.forName("com.mysql.jdbc.Driver");

            // DriverManager is used to handle a set of JDBC drivers
            // getConnection establishes a connection to the database
            // You must also pass the userid and password for the database            
            String url = "jdbc:mysql://localhost:3306/charity";
            conn = DriverManager.getConnection (url,"root","password");

            // Statement objects executes a SQL query
            // createStatement returns a Statement object            
            Statement sqlState = conn.createStatement();

            // This is the query I'm sending to the database
            String selectStuff = "SELECT `name`, `charity`, `amount` FROM `charity`.`donations` ";                  

            // A ResultSet contains a table of data representing the
            // results of the query. It can not be changed and can 
            // only be read in one direction            
            rows = sqlState.executeQuery(selectStuff);

            // Temporarily holds the row results            
            Object[] tempRow;

            // next is used to iterate through the results of a query            
            while(rows.next())

            // Gets the column values based on class type expected
            tempRow = new Object[]rows.getString(1), rows.getString(2), rows.getDouble(3) ;

            // Adds the row of data to the end of the model             
            dTableModel.addRow(tempRow);                

        
            // Successfully loaded, message the user
            message1.setText("<html><font color='red'>Database Info Loaded</font>");
            message2.setText("");
     
        catch (SQLException ex) 
                    
            // String describing the error          
            System.out.println("SQLException: " + ex.getMessage());

            // Vendor specific error code            
            System.out.println("VendorError: " + ex.getErrorCode());
         
        catch (ClassNotFoundException e) 
        
            // Executes if the driver can't be found
            System.out.println("Driver Cannot be found");
            e.printStackTrace();
        

        // Create a JTable using the custom DefaultTableModel       
        JTable table = new JTable(dTableModel);

        // Increase the font size for the cells in the table        
        table.setFont(new Font("Serif", Font.PLAIN, 16));

        // Increase the size of the cells to allow for bigger fonts        
        table.setRowHeight(table.getRowHeight()+5);

        // Allows the user to sort the data     
        table.setAutoCreateRowSorter(true);

        // right justify amount column
        TableColumn tc = table.getColumn("amount");
        RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
        tc.setCellRenderer(rightRenderer);      

        // Disable auto resizing
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // Set the width for the columns        
        TableColumn col1 = table.getColumnModel().getColumn(0);
        col1.setPreferredWidth(200);

        TableColumn col2 = table.getColumnModel().getColumn(1);
        col2.setPreferredWidth(275);

        TableColumn col3 = table.getColumnModel().getColumn(2);
        col3.setPreferredWidth(75);     

        // Put the table in a scrollpane and add scrollpane to the frame          
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(552, 400));
        this.add(scrollPane, BorderLayout.CENTER);
       

    // To change justification to the right
    class RightTableCellRenderer extends DefaultTableCellRenderer    
          public RightTableCellRenderer()   
            setHorizontalAlignment(JLabel.RIGHT);  
                   
           

【问题讨论】:

您能否发布显示您的ActionListener 和注册地址的JButton 的代码? 我已经添加了您询问的部分,但它们非常基本,认为它们对桌子没有任何影响 【参考方案1】:

无论用户按多少次按钮,我怎样才能让它只加载一个表?

表格和滚动窗格只应在构建 GUI 组件时创建一次。然后,当您要更改数据时,只需更改现有表的模型即可:

table.setModel( updatedModel );

【讨论】:

所以将 jTable 的内容移动到不同的方法中,然后根据我是否希望显示表格来更改可见性?

以上是关于TableModel,导致 Java JFrame 中出现重复的数据库信息的主要内容,如果未能解决你的问题,请参考以下文章

swing_tableModel 创建表格

在另一个 JFrame 中使用 JButton 刷新 JTable?

java的table里怎么加checkbox

JFrame关闭方法的问题

java tablemodel怎么样实现表格合并

MVC 模式和 Swing