虽然您最初提到使用两个 JFrame,但您的设计似乎涉及一个 JFrame (frame1)和一个用于显示搜索结果的 JDialog。这种区别很重要,因为 JDialog 依赖于其父窗口。
要在 GUI 对象(包括 JFrame 和 JDialog)之间传递引用,您可以使用标准 Java 引用。当一个窗口打开另一个窗口时,父窗口通常会保留对子窗口的引用,并可以调用其方法。
确定何时从子窗口检索数据窗口取决于其类型:
这里一个简单的示例,允许框架 1 中的按钮打开 JDialog 并使用在 JDialog 的 JTextField 中输入的文本填充框架 1 中的 JTextField:
<code class="java">import java.awt.Window; import java.awt.Dialog.ModalityType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class WindowCommunication { public static void main(String[] args) { java.awt.EventQueue.invokeLater(() -> createAndShowUI()); } private static void createAndShowUI() { JFrame frame1 = new JFrame("frame1"); MyFramePanel panel1 = new MyFramePanel(); frame1.getContentPane().add(panel1); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.pack(); frame1.setLocationRelativeTo(null); frame1.setVisible(true); } static class MyFramePanel extends JPanel { private JTextField textField; private JButton openDialogButton; private JDialog dialog; private MyDialogPanel dialogPanel; public MyFramePanel() { textField = new JTextField(10); textField.setEditable(false); textField.setFocusable(false); openDialogButton = new JButton("Open Dialog"); openDialogButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openDialogAction(); } }); add(textField); add(openDialogButton); } private void openDialogAction() { if (dialog == null) { Window win = SwingUtilities.getWindowAncestor(this); if (win != null) { dialog = new JDialog(win, "My Dialog", ModalityType.APPLICATION_MODAL); dialogPanel = new MyDialogPanel(); dialog.getContentPane().add(dialogPanel); dialog.pack(); dialog.setLocationRelativeTo(null); } } dialog.setVisible(true); // Here, after the modal dialog is disposed, the text from the // dialog's JTextField is retrieved and set into this JDialog's JTextField. textField.setText(dialogPanel.getFieldText()); } } static class MyDialogPanel extends JPanel { private JTextField textField; private JButton okButton; public MyDialogPanel() { textField = new JTextField(10); okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { okButtonAction(); } }); add(textField); add(okButton); } public String getFieldText() { return textField.getText(); } private void okButtonAction() { Window win = SwingUtilities.getWindowAncestor(this); if (win != null) { win.dispose(); } } } }</code>
要从 JTable 检索数据,您可以使用类似的技术,但您可能需要考虑其他因素,例如表格行选择。
以上是以下是一些基于问题的标题,它们抓住了本文的精髓: * 如何在 Java Swing 中的 JFrame 和 JDialog 之间传递值? * 从子窗口检索数据:JFrames、JDialogs、的详细内容。更多信息请关注PHP中文网其他相关文章!