我想在主窗口textField 中写的消息,发送到子窗口的textArea中,并在子窗口textArea中显示我所输出的消息!
我试过在子窗中调用主窗口的方法!可是不知道怎么调用,本人刚学习java,希望哪个大侠能帮我分析一下,最好
能写个代码,在子窗口的类中怎样调用主窗口中的方法!!谢啦!!
------解决方案--------------------
父窗口提供对应TextField的getter方法,然后子窗口初始化的时候将父窗口的实例传递进去
具体代码你可以参考下
- Java code
import javax.swing.*;import java.awt.*;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;public class FatherFrame extends JFrame implements ActionListener { private JButton btn=new JButton("click"); public JTextField getJtx() { return jtx; } private JTextField jtx=new JTextField(15); private JDialog dialog=null; public FatherFrame(String title){ super(title); Container c=this.getContentPane(); c.setLayout(new FlowLayout()); c.add(jtx); c.add(btn); btn.addActionListener(this); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { dialog=new ChildDialog(this);// dialog.getParent(); } public static void main(String[] args) { new FatherFrame("demo"); }}class ChildDialog extends JDialog{ private FatherFrame father=null; private JLabel label=null; private JTextArea jta=new JTextArea(); public ChildDialog(FatherFrame fatherFrame){ this.father=fatherFrame; jta.setText(father.getJtx().getText()); label=new JLabel("以下是从父窗口获得的信息:"); this.getContentPane().setLayout(new FlowLayout()); this.getContentPane().add(label); this.getContentPane().add(jta); this.pack();// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.setLocationRelativeTo(null); }}