雖然您最初提到使用兩個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中文網其他相關文章!