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

TableModel,导致Java JFrame中的数据库信息重复,java,swing,jdbc,jframe,tablemodel,Java,Swing,Jdbc,Jframe,Tablemodel,我在一个JFrame中设置了这个方法,当用户按下按钮“加载文件”时调用它;但是,当用户再次按下按钮时。他们在第一个表的下面有另一个表,所以所有的信息都会被复制,并扩展到我的“不可调整大小”框架之外 无论用户按下按钮多少次,我如何让它只加载一个表 JButton btnLoad = new JButton("Load File") private void GetAction() { ActionHandler handler = new ActionHandler();

我在一个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);  
        }           
    }       
JButton btnLoad=newjbutton(“加载文件”)
私有void GetAction()
{
ActionHandler=新的ActionHandler();
btnLoad.addActionListener(处理程序);
}
私有类ActionHandler实现ActionListener
{       
已执行的公共无效操作(操作事件evt)
{
字符串incmd=evt.getActionCommand();
if(incmd.equals(“加载文件”)//如果按下加载文件按钮
数据库加载();
else if(incmd.equals(“Exit”)//如果按下Exit按钮
系统出口(0);
}
}
私有void数据库加载()
{
尝试
{
//该驱动程序允许您使用Java查询数据库
//forName为您动态加载类
Class.forName(“com.mysql.jdbc.Driver”);
//DriverManager用于处理一组JDBC驱动程序
//getConnection建立到数据库的连接
//您还必须传递数据库的用户ID和密码
String url=“jdbc:mysql://localhost:3306/charity";
conn=DriverManager.getConnection(url,“根”,“密码”);
//语句对象执行SQL查询
//createStatement返回一个语句对象
语句sqlState=conn.createStatement();
//这是我发送到数据库的查询
String selectStuff=“选择'name'、'charity'、'amount`来自'charity`.'investments`”;
//ResultSet包含一个数据表,表示
//查询的结果。它不能更改,并且可以
//只能从一个方向读取
rows=sqlState.executeQuery(selectStuff);
//暂时保存行结果
对象[]临时行;
//next用于遍历查询结果
while(rows.next()){
//根据预期的类类型获取列值
tempRow=newobject[]{rows.getString(1),rows.getString(2),rows.getDouble(3)};
//将数据行添加到模型的末尾
dTableModel.addRow(tempRow);
}
//已成功加载,请向用户发送消息
message1.setText(“加载的数据库信息”);
message2.setText(“”);
} 
catch(SQLException-ex)
{            
//描述错误的字符串
System.out.println(“SQLException:+ex.getMessage());
//供应商特定错误代码
System.out.println(“vendoerror:+ex.getErrorCode());
} 
catch(classnotfounde异常)
{
//如果找不到驱动程序,则执行
System.out.println(“找不到驱动程序”);
e、 printStackTrace();
}
//使用自定义DefaultTableModel创建JTable
JTable table=新的JTable(dTableModel);
//增加表格中单元格的字体大小
表.setFont(新字体(“衬线”,Font.PLAIN,16));
//增加单元格的大小以允许使用更大的字体
table.setRowHeight(table.getRowHeight()+5);
//允许用户对数据进行排序
表.setAutoCreateRowSorter(真);
//右对齐金额列
TableColumn tc=table.getColumn(“金额”);
RightTableCellRenderer rightRenderer=新的RightTableCellRenderer();
tc.setCellRenderer(右渲染器);
//禁用自动调整大小
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//设置列的宽度
TableColumn col1=table.getColumnModel().getColumn(0);
col1.设置首选宽度(200);
TableColumn col2=table.getColumnModel().getColumn(1);
col2.设置首选宽度(275);
TableColumn col3=table.getColumnModel().getColumn(2);
col3.设置首选宽度(75);
//将表格放在滚动窗格中,并将滚动窗格添加到框架中
JScrollPane scrollPane=新的JScrollPane(表);
scrollPane.setPreferredSize(新维度(552400));
添加(滚动窗格,BorderLayout.CENTER);
}   
//右转
类RightTableCellRenderer扩展了DefaultTableCellRenderer{
public RightTableCellRenderer(){
设置水平对齐(JLabel.RIGHT);
}           
}       
无论用户按下按钮多少次,我如何让它只加载一个表

    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);  
        }           
    }       
在构建GUI组件时,表和滚动窗格只应创建一次。然后,如果要更改数据,只需更改现有表的模型即可:

table.setModel( updatedModel );
无论用户按下按钮多少次,我如何让它只加载一个表

    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);  
        }           
    }       
在构建GUI组件时,表和滚动窗格只应创建一次。然后,如果要更改数据,只需更改现有表的模型即可:

table.setModel( updatedModel );

你能发布显示你的
ActionListener
和注册的
JButton
的代码吗?我已经添加了你所问的部分,但是它们非常基本,并且认为它们对表格没有任何影响。你能发布显示你的
ActionListener
和注册的
JButton
的代码吗?我已经添加了你问的部分