最初に 2 つの JFrame を使用すると述べましたが、設計には 1 つの JFrame (frame1) が含まれているようです。検索結果を表示するための JDialog です。 JDialog は親ウィンドウに依存するため、この区別は重要です。
JFrame や JDialog を含む GUI オブジェクト間で参照を渡すには、標準の Java 参照を使用できます。あるウィンドウが別のウィンドウを開くと、通常、親ウィンドウは子ウィンドウへの参照を保持し、そのウィンドウ上のメソッドを呼び出すことができます。
子からデータを取得するタイミングの決定ウィンドウはそのタイプによって異なります:
は次のとおりです。 Frame1 のボタンで JDialog を開き、JDialog の JTextField に入力されたテキストを Frame1 の 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 の間で値を渡すにはどうすればよいですか? * 子ウィンドウからのデータの取得: JFrame、JDialog、の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。