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

标签 java swing

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

所以我的问题如下:

我有一个名为 Main_Window 的主 JFrame,其中有一个 JTable 和一个 JButton。单击按钮后,另一个 JFrame (Update_Window) 将打开,我可以从中更新表。 Update_Window JFrame 有两个文本字段和一个SUBMIT按钮。

简单地说,我想从 Update_Window JFrame 更新 Main_Window 中的 JTable。在 TextFields 中输入内容并使用按钮提交后,数据应该出现在 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],以便我们更好地识别您的问题。

关于java - 单击按钮时从另一个 JFrame 调用 JFrame 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57151723/

相关文章:

java - 复制到全局剪贴板不适用于 Ubuntu 中的 Java

java - PaintComponent 不在 Jpanel 上绘制 Sprite

java - JTextField 不工作

java - 如何使用 android studio 以编程方式记录 Android 设备的所有入站和出站连接

java - 将 Editable 作为 EditText.getText() 方法的返回类型的目的是什么?

java - 错误的参数传递给 .ksh

java - 使用java实现排序功能

java - 正则表达式字符串中的多个IP地址

java - JCombobox 根据 true/false 调整文本

java - 为什么我的 jFrame 只在我调整窗口大小时更新?