首页  >  文章  >  Java  >  如何在 Java 应用程序中的 JFrame 之间有效地传输数据,特别是在处理用户与子 JFrame 中的搜索框和 JTable 的交互并需要返回选定的 r 时

如何在 Java 应用程序中的 JFrame 之间有效地传输数据,特别是在处理用户与子 JFrame 中的搜索框和 JTable 的交互并需要返回选定的 r 时

Susan Sarandon
Susan Sarandon原创
2024-10-26 14:53:021000浏览

How do you effectively transfer data between JFrames in a Java application, specifically when handling user interactions with a search box and JTable in a child JFrame and needing to return selected row values to the parent JFrame?

在 JFrame 之间传递数据

在 JFrame 之间传递值对于协调复杂 Java 应用程序中的数据交换至关重要。本文解决了一种常见场景,其中用户与包含文本字段的 JFrame 进行交互,打开带有搜索框和 JTable 的第二个 JFrame,并且需要将选定的行值传输回第一个 JFrame。

理解 JFrame 通信

要在 JFrame 之间传递值,识别父窗口和子窗口之间的内在关系至关重要。当一个 JFrame 打开另一个 JFrame 时,父框架保留对子框架的引用。这允许父框架访问子框架的方法来检索数据。

实现值传递

在给定的场景中,最好的方法是在内部使用侦听器子 JFrame 来检测表行选择。选择后,侦听器应提取所需的值并使用存储的引用通知父 JFrame。

或者,如果子 JFrame 是模式对话框,则可以延迟值传递,直到对话框被处理。在这种情况下,子框架应该收集值并通过对父框架的方法调用将它们返回。

示例实现

考虑以下 Java 代码示例,它实现了 JFrame 之间的基本值传递场景:

<code class="java">import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ValuePassing {

    private static void createAndShowUI() {
        JFrame parentFrame = new JFrame("Parent Frame");
        parentFrame.getContentPane().add(new ParentPanel());
        parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        parentFrame.pack();
        parentFrame.setLocationRelativeTo(null);
        parentFrame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

class ParentPanel extends JPanel {

    private JTextField textField;

    ParentPanel() {
        JButton openButton = new JButton("Open Child Frame");
        openButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openChildFrame();
            }
        });

        textField = new JTextField(10);

        add(openButton);
        add(textField);
    }

    // Method to open the child frame as a modal dialog
    private void openChildFrame() {
        JDialog childDialog = new JDialog(JFrame.getFrames()[0], "Child Dialog", true);
        childDialog.getContentPane().add(new ChildPanel());
        childDialog.pack();
        childDialog.setLocationRelativeTo(null);
        childDialog.setVisible(true); // Here, the modal dialog takes over

        // Value passing occurs when the dialog is disposed
        textField.setText(childDialog.getContentPane().getComponent(0).toString());
    }
}

class ChildPanel extends JPanel {

    String getValue() {
        return "value from child";
    }
}</code>

此示例演示如何打开具有模式对话框关系的子 JDialog、从子 JDialog 检索值以及更新父框架中的文本字段当对话框关闭时。

以上是如何在 Java 应用程序中的 JFrame 之间有效地传输数据,特别是在处理用户与子 JFrame 中的搜索框和 JTable 的交互并需要返回选定的 r 时的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn