在按钮单击时从另一个 JFrame 调用 JFrame 方法



我在堆栈溢出上搜索了我问题的类似答案,但它们都没有帮助我。

所以我的问题如下:

我有一个主要的JFrame叫做Main_Window,上面我有一个JTable和一个JButton。单击按钮后,将打开另一个 JFrame(Update_Window(,从中我可以更新表格。JFrame Update_Window有两个文本字段和一个SUBMIT按钮。

简而言之,我想从Update_Window JFrame Main_Window更新我的JTable。在文本字段中键入内容并使用按钮提交后,数据应该出现在Main_Window的 JTable 中,但它不起作用。

这是我Main_Window JFrame:

    private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Update_Window newWindow = new Update_Window();
        newWindow.setVisible(true);
        newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
    }  
    public void putDataIntoTable(Integer data, int row, int col) {
        jTable1.setValueAt(data,row,col);
    }

这是我Update_Window JFrame:

    private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
        quantity = Integer.parseInt(quantityTextField.getText());
        price = Integer.parseInt(priceTextField.getText());
        Main_Window mw = new Main_Window();
        mw.putDataIntoTable(price,3,2);
    }     

我认为我的问题Main_Window mw = new Main_Window();在这里,因为这会创建一个新实例,并且不会将数据添加到正确的窗口中,或类似的东西。

是的,你是对的。Main_Window mw = new Main_Window();的台词肯定是错误的。

更好的解决方案是:

public class UpdateWindow extends JFrame {
    private final MainWindow mainWindow;
    public UpdateWindow(MainWindow mainWin) {
        mainWindow = mainWin;
    }
    private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
        quantity = Integer.parseInt(quantityTextField.getText());
        price = Integer.parseInt(priceTextField.getText());
        mainWindow.putDataIntoTable(price,3,2);
    }     
}

您还需要更正构造函数的调用以进行UpdateWindow

private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    UpdateWindow newWindow = new UpdateWindow(this);
    newWindow.setVisible(true);
    newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);  
}  

请注意:我已经按照 Java 命名约定的建议更正了您的类名。 Main_Window -> MainWindowUpdate_Window -> UpdateWindow .

当我的建议不能解决您的问题时,请提供[mcve],以便我们更好地识别您的问题。

最新更新