首页 > 解决方案 > 如何在不“关闭”第一个 JFrame 的情况下从另一个 JFrame 刷新 JFrame 的 JTable?

问题描述

我正在尝试在不关闭主 JFrame 的情况下从另一个 JFrame 更新 JTable。主 JFrame 有 JTable,第二个 JFrame 有文本字段和获取数据以更新主窗口中的 JTable 的“更新”按钮,一切正常,但如果我希望 JTable 正确更新,我必须将主框架的可见性设置为“false”,并在“更新”按钮完成操作时将其更改为“true”,因此,基本上主窗口关闭,更新操作后重新打开。我想知道是否有任何方法可以在不关闭主 JFrame 的情况下进行更新。

打开第二个框架的主框架中的按钮:

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    this.setVisible(false);
    
    UpdtFrame frame = new UpdtFrame();
    
    frame.setVisible(true);
    
}

第二个 JFrame 中要更新的按钮:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
        Object[] info = {jTextField1.getText(), Double.parseDouble(jTextField2.getText()), Integer.parseInt(jTextField3.getText())}; //get the info from the text fields
        
        updtProdList(jTextField1.getText(), info);
        
        inter.setVisible(true); //object of the main JFrame, opens the frame after do the 
                                //update
        
        this.dispose();
}

更新操作:

public void updtProdList(String name, Object[] info)
{
    for(int i = 0; i < inter.jTable1.getRowCount(); i++)
        {
            if(inter.jTable1.getValueAt(i, 0).toString().equalsIgnoreCase(name))
            {
                for(int j = 0; j < info.length; j++)
                {
                    inter.jTable1.setValueAt(info[j], i, j);
                }
                
                break;
            }
        }
        
        inter.jTable1.revalidate(); //update the table on the main frame
}

我不知道如何在不关闭框架并再次打开它的情况下进行 JTable 更新,不胜感激。

标签: javaswingjava-8jframejtable

解决方案


我一直在阅读评论中提供的所有材料,感谢我能够使用 JDialog 找到解决方案。

因此,在创建的 JDialog 的类中,将主 JFrame 实例设置为 JDialog 的“父级”很重要:

public class UpdtDialog extends javax.swing.JDialog {
    MainJFrame  frame = new MainJFrame();

    public UpdtDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocation(50, 300);
        setSize(400, 300);
        frame = (MainJFrame) parent;
    }

    //then all the code necessary, in my case it will be button and the 
    //update method
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //TODO
    }

    public void updtProdList(String name, Object[] info){
        //TODO
    }
}

在主框架上,显示 JDialog 的按钮将具有 JDialog 类的实例。

public class InterfazSwing extends javax.swing.JFrame {

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         UpdtDialog diag = new UpdtDialog(this, true);
         diag.setVisible(true);
    }

}

这样,我就能够解决我在更新 JTable 时面临的问题。


推荐阅读