现在我有1,2个窗口1窗口按jbutton new(窗口2),关将窗口1   setVisible(false);现在我要通过窗口2重新将窗口1设为 setVisible(true); 怎么得到窗口1这个对象

解决方案 »

  1.   

    你创建窗体2的时候需要在窗体1中定义一个成员变量 用来接收窗体1对象也就是把窗体1做为窗体2的一个属性创建时把this 传给它,这里的this带表窗体1
    new JFrame2(this)
      

  2.   


    package com;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JButton; 
    import javax.swing.JFrame;public class CSDNSwing2  extends JFrame   {
    public CSDNSwing2() {
    JButton button = new JButton("创建Frame2");
    button.addActionListener(new Testlistener(this));
    this.add(button);
    this.setTitle("窗体1");
    this.setSize(200,200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    }
    public static void main(String[] args) {
    new CSDNSwing2();
    }
    }class Testlistener implements ActionListener{
    private JFrame frame1;
    public Testlistener(JFrame frame1) {
    this.frame1 = frame1;
    }
    public void actionPerformed(ActionEvent e) {
    new JFrame2(frame1);
    }

    }//窗体2
    class JFrame2 extends JFrame{
    private JFrame frame1;
    public JFrame2(JFrame frame1) {
    this.frame1 = frame1;

    frame1.setVisible(false);
    JButton button = new JButton("创建Frame1");
    button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) {
    JFrame2.this.frame1.setVisible(true);
    JFrame2.this.setVisible(false);
    }

    });

    this.add(button);
    this.setTitle("窗体2");
    this.setSize(200,200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    }
    }
      

  3.   

    class JFrame2 extends JFrame{
        private JFrame frame1;
        public JFrame2(JFrame frame1) {
            this.frame1 = frame1;
            
            frame1.setVisible(false);
            JButton button = new JButton("创建Frame1");
            button.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent e) {
                    JFrame2.this.frame1.setVisible(true);
                    JFrame2.this.setVisible(false);
                }
                
            });
            
            this.add(button);
            this.setTitle("窗体2");
            this.setSize(200,200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        }
    }