简体   繁体   English

如何通过单击第一个Java Windows应用程序(Jframe)中的菜单项启动第二个Jframe

[英]How to start 2nd Jframe by click menu item in 1st java windows application (Jframe)

I am using eclipse 4.2 with Java. 我正在Java中使用eclipse 4.2。

I have 2 java program : AppWin.java Form1.java 我有2个Java程序: AppWin.java Form1.java

AppWin.java is gui windows application with menu/menu item1 . AppWin.java是带有menu/menu item1 gui Windows应用程序。

Form1.java is a Gui Jframe Form1.java是Gui Jframe

I like to call Form1.java from AppWin.java by click the menu/menu item1 . 我想通过单击menu/menu item1AppWin.java调用Form1.java When close Form1.java , it is back to AppWin.java . 关闭Form1.java ,它将返回到AppWin.java

This is something like MDIFORM . 这就像MDIFORM一样。 I really cannot find answer. 我真的找不到答案。 Please help , if you know eclipse menu. 请帮助,如果您知道蚀菜单。

Thanks 谢谢

package top;

import java.awt.EventQueue;

public class AppWin {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AppWin window = new AppWin();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

... ...

With your help, I made a big step. 在您的帮助下,我迈出了一大步。 Thanks to all of you! 感谢大家!

Next is my final demo, in windows 7, eclipse 4.2, java Gui Hope it is helpful to others. 接下来是我的最终演示,在Windows 7,Eclipse 4.2,Java Gui中,希望对其他人有帮助。

There are 3 parts : AppWin, Form1, Form2. 共有3个部分:AppWin,Form1,Form2。 AppWin is top main which call Form1 and Form2 with menu/item. AppWin是使用菜单/项目调用Form1和Form2的主要工具。

//1
package top;

import java.awt.EventQueue;

public class AppWin {

    private JFrame frame;

    private Form1 form1;
    private Form2 form2;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    AppWin window = new AppWin();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public AppWin() {
        initialize();
        form1 = new Form1();
        form2 = new Form2();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        JMenu mnNewMenu = new JMenu("Menu1");
        menuBar.add(mnNewMenu);

        JMenuItem mntmNewMenuItem = new JMenuItem("menu item1");
        mntmNewMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                form1.setVisible(true);
            }
        });
        mnNewMenu.add(mntmNewMenuItem);

        JMenuItem mntmNewMenuItem_1 = new JMenuItem("menu item2");
        mntmNewMenuItem_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                form2.setVisible(true);
            }
        });
        mnNewMenu.add(mntmNewMenuItem_1);

        JMenu mnNewMenu_1 = new JMenu("Menu2");
        menuBar.add(mnNewMenu_1);

        JMenuItem mntmMenuItem = new JMenuItem("Menu item3");
        mnNewMenu_1.add(mntmMenuItem);
    }

}

//2
package top;

import java.awt.BorderLayout;

public class Form1  extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Form1 frame = new Form1();
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Form1() {
//      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JLabel lblNewLabel = new JLabel("this Form1");
        contentPane.add(lblNewLabel, BorderLayout.WEST);

        textField = new JTextField();
        contentPane.add(textField, BorderLayout.CENTER);
        textField.setColumns(10);

        JButton btnNewButton = new JButton("New button");
        contentPane.add(btnNewButton, BorderLayout.EAST);
    }

}

//3
package top;

import java.awt.BorderLayout;

public class Form2 extends JDialog {

    private final JPanel contentPanel = new JPanel();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {
            Form2 dialog = new Form2();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the dialog.
     */
    public Form2() {
        setBounds(100, 100, 450, 300);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setLayout(new FlowLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        {
            JLabel lblThisForm = new JLabel("This Form2");
            contentPanel.add(lblThisForm);
        }
        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton okButton = new JButton("OK");
                okButton.setActionCommand("OK");
                buttonPane.add(okButton);
                getRootPane().setDefaultButton(okButton);
            }
            {
                JButton cancelButton = new JButton("Cancel");
                cancelButton.setActionCommand("Cancel");
                buttonPane.add(cancelButton);
            }
        }
    }

}

Thanks again 再次感谢

You better use JDesktopPane + JInternalFrame for that purpose instead. 为此,您最好使用JDesktopPane + JInternalFrame Here's a quick sample. 这是一个快速示例。

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;

    import javax.swing.AbstractAction;
    import javax.swing.JDesktopPane;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;

    public class JInternalFrameSample {

        private JPanel pnlMain;
        private JDesktopPane desk;

        public JInternalFrameSample(){
            pnlMain = new JPanel(new BorderLayout()){
                @Override public Dimension getPreferredSize(){
                    return new Dimension(600,600);
                }
            };
            desk = new JDesktopPane();

            JMenuBar bar = new JMenuBar();
            JMenu menu = new JMenu("Internal Frame");
            JMenuItem item = new JMenuItem();

            item.setAction(new AbstractAction("Create New") {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    JInternalFrame iFrame = new JInternalFrame("Created from Menu");
                    iFrame.setResizable(true);
                    iFrame.setClosable(true);
                    iFrame.setIconifiable(true);
                    iFrame.setSize(new Dimension(300, 300));
                    iFrame.setLocation(0, 0);

                    //iFrame.getContentPane().setLayout(new BorderLayout());
                    //iFrame.getContentPane().add( new YourCustomUI().getUI() );

                    iFrame.setVisible(true);
                    desk.add(iFrame);
                }
            });


            menu.add(item);
            bar.add(menu);

            pnlMain.add(bar, BorderLayout.PAGE_START);
            pnlMain.add(desk, BorderLayout.CENTER);
        }

        private JPanel getUI(){
            return pnlMain;
        }

        public static void main(String[] args){
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Demo");
                    frame.getContentPane().setLayout(new BorderLayout());
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.getContentPane().add(new JInternalFrameSample().getUI());
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }
    }

See also : How to Use Internal Frames 另请参阅: 如何使用内部框架

If you do not like the JDesktopPane and JInternalFrame solution, just use your AppWin JFrame as is, and open modal JDialogs for the rest of the forms, instead of JFrames. 如果您不喜欢JDesktopPane和JInternalFrame解决方案,只需按原样使用AppWin JFrame,然后为其余表单(而不是JFrame)打开模式JDialogs。 Modal dialogs can float around the desktop and do not allow you to click your AppWin, until they are closed. 模式对话框可以在桌面周围浮动,并且除非关闭它们,否则不允许您单击AppWin。

It is usually better to use just one main JFrame for an application, unless you have some wizard application that moves progressively from one JFrame to the other and back. 通常最好只对一个应用程序使用一个主JFrame,除非您有一些向导应用程序从一个JFrame逐渐移到另一个JFrame,然后又移回另一个。 Even with a wizard app, you can stick with one JFrame and update progressively just the ContentPane with JPanels. 即使使用向导应用程序,您也可以坚持使用一个JFrame并仅使用JPanels逐步更新ContentPane。

Here is the AppWin JFrame: 这是AppWin JFrame:

public class AppWin extends javax.swing.JFrame {
    private Form1 form1;
    private Form1 form2;
    ...
    private FormN formN;

    public AppWin() {
        initComponents();
        form1 = new Form1(this, true);
        form2 = new Form2(this, true);
        ...
        formN = new FormN(this, true);
    }
    ...
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        form1.setVisible(true);
    }

And here is your Form1 JDialog: 这是您的Form1 JDialog:

public class Form1 extends javax.swing.JDialog {
    public Form1(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    ...
    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
        setVisible(false);
    }      

I only use NetBeans for GUI building because that's more convenient. 我只使用NetBeans进行GUI构建,因为这样更方便。 In the following I can tell you how to achieve what you want to do but I can't tell you how to layout all the components because NetBeans do that for me. 在下面的内容中,我可以告诉您如何实现所需的操作,但是由于NetBeans可以为我完成这些操作,因此我无法告诉您如何布置所有组件。

So basically you want to 1. show secondFrame by clicking a menuitem and then close mainFrame, 2. show mainFrame after closing secondFrame, yes? 因此,基本上,您想要1.通过单击菜单项然后关闭mainFrame来显示secondFrame,2.关闭secondFrame之后再显示mainFrame,是吗? Then, the key is to pass the reference of mainFrame to secondFrame, and write your own method of formClosing event of secondFrame. 然后,关键是将mainFrame的引用传递给secondFrame,并编写您自己的secondFrame的formClosing事件方法。 Something like this: 像这样:

In the menuItem method in your mainframe: 在大型机的menuItem方法中:

private void menuItemActionPerformed(java.awt.event.ActionEvent evt) {
    //pass 'this' frame's (mainFrame) reference to the secondFrame
    SecondFrame newFrame = new SecondFrame(this);
    newFrame.setVisible(true); //show the secondFrame
    this.setVisible(false);  //hide this frame (mainFrame)
}

In your secondFrame: 在您的secondFrame中:

public class SecondFrame extends javax.swing.JFrame {

private MainFrame mainFrame;

//define your own constructor that can use mainFrame's reference
public SecondFrame(MainFrame mainFrame) {
    initComponents();
    this.mainFrame = mainFrame;
}

private void initComponents(){
    //bind your own event for closing second frame
    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            formWindowClosing(evt);
        }
    });

    /***********your stuff***************/
}

//show mainFrame when closing this frame and then dispose this frame
private void formWindowClosing(java.awt.event.WindowEvent evt) {
    mainFrame.setVisible(true);
    this.dispose();
}

} }

The codes above is for disposing the secondFrame when closing it. 上面的代码用于在关闭第二个框架时将其放置。 If you just want to hide the secondFrame when closing for future use, then the codes will be slightly different. 如果您只想在关闭时隐藏secondFrame以便将来使用,则代码将略有不同。 Let me know what you up to. 让我知道你在做什么。

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { 私人无效jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt){
form1.setVisible(true); form1.setVisible(true); dispose(); dispose(); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java awt计算器+/-,如何用-替换+:第一次单击=“-”,第二次单击=“ +”,依此类推 - Java awt calculator +/- , how to replace + with - : 1st click = “-”, 2nd click = “+” and so on 从Android中的第一个应用程序开始第二个应用程序的活动 - Start Activity of 2nd app from 1st app in android Java Web应用程序在第二次登录后销毁第一次登录会话 - java web application destroy 1st login session after 2nd login 从适配器单击第一个选项卡recyclerview项时,如何为第二个选项卡设置动画? - how to animate to 2nd tab when 1st tab recyclerview item is clicked from adapter? Java多线程第二线程等待第一 - Java multithreading 2nd thread waiting for 1st Java继承:第2个实例调用第1个实例方法 - Java Inheritance : 2nd instance calls 1st instance method 在 Java 中的字符串中查找第 1 次和第 2 次出现的正则表达式 - Finding the 1st and 2nd occurrence of a regex in a string in Java 在 java 中将第一个数组值乘以 1,将第二个值乘以 3 - Multiply 1st array value with 1 and 2nd value with 3 in java 你如何让应用程序读取第二个单词的第一个字母 - How do you make the application get to read the 1st letter of the 2nd word 如何在Java Swing中从第一个面板获取价值并插入第二个面板 - How to get value from 1st panel and insert in 2nd panel in Java Swing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM