java - 从另一个类中处理 JFrame

标签 java swing jframe dispose

如何从另一个类中处理 JFrame?下面列出了我的代码。 我使用 Netbeans 生成表单来生成窗口。我想使用另一个类进行处理(名称是 needDispose)。

    public class needDispose {
         /**
          *Call for dispose frame
          */
        public static void disposeMyFrame(){
            myEasyFrame.getMainFrame.dispose(); // DOESNT WORK
        }
    }

NETBEANS 生成 (重要方法是 getMainFrame() )

import javax.swing.JFrame;


public class myEasyFrame extends javax.swing.JFrame {
    /*
     * Get frame
     */
    public final JFrame getMainFrame() {
        return this;
    }

    /**
     * Creates new form myEasyFrame
     */
    public myEasyFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("CLICK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        needDispose.disposeMyFrame();
    }                                        


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(myEasyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new myEasyFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

最佳答案

下面是如何从另一个本身就是 JFrame 的类中处理 JFrame 的示例:

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Demo
{
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      @Override
      public void run()
      {
        FrameA one = new FrameA();
        FrameB two = new FrameB(one);

        one.setVisible(true);
        two.setVisible(true);
      }
    });
  }
}

class FrameA extends JFrame
{
  private static final long serialVersionUID = 1812279930292019387L;

  public FrameA()
  {
    super("Frame A");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    setLocationRelativeTo(null);

    setResizable(false);
  }
}

class FrameB extends JFrame
{
  private static final long serialVersionUID = 5126089271972476434L;

  public FrameB(final JFrame otherFrame)
  {
    super("Frame B");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    setLayout(new GridBagLayout());
    setLocationRelativeTo(otherFrame);

    JButton button = new JButton("Dispose Other");
    button.addActionListener(new ActionListener()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        otherFrame.dispose();
      }
    });

    add(button);

    setResizable(false);
  }
}

关于java - 从另一个类中处理 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21966935/

相关文章:

java - 找不到适合 jdbc :oracle:thin:@localhost:1521:XE when running web application 的驱动程序

java - 图表上的 setFont 问题 (JFreeChart)

java - 使用 JButton 的无锁循环

java - 如何在 JFileChooser 窗口中选择多个文件

java - 如何使用 platform.runlater() 禁用一个 web View 中的链接/超链接/导航并在 java 中的另一个 web View 中打开该链接/超链接/导航

java - 如何使用 JPA ManyToMany 防止连接表中的重复条目

java - 使用套接字 I/O 阻塞操作中断/停止线程

java - 如何使 JButtons 的这些 JLabels 不可见

java - JTable:如何初始化一个空单元格(类型为 int/float...)以允许用户在 JTable 中输入数字?

java - 在 Jframe 中使用 menuItem 切换 jpanels