繁体   English   中英

如何在主机架中打开另一个框架?

[英]How to open another frame in main frame?

我创建了两个jframe main_frame和sub_frame,其中main_frame包含一个jbutton。 现在我希望该按钮在同一帧(main_frame)中打开sub_frame并设置main_frame disable直到打开sub_frame。 请注意,我不希望main_frame设置为setVisible(false)。

我建议您使用CardLayout

您可以使用多个JPanel并在它们之间进行切换,而不是使用多个JFrame。

这是一个例子:

package main.frames;

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;

public MainFrame()
{
    JButton showOtherPanelBtn = new JButton("Show Other Panel");
    JButton backToHomeBtn = new JButton("Show Home Panel");

    cl = new CardLayout(5, 5);
    homeContainer = new JPanel(cl);
    homeContainer.setBackground(Color.black);

    homePanel = new JPanel();
    homePanel.setBackground(Color.blue);
    homePanel.add(showOtherPanelBtn);

    homeContainer.add(homePanel, "Home");

    otherPanel = new JPanel();
    otherPanel.setBackground(Color.green);
    otherPanel.add(backToHomeBtn);

    homeContainer.add(otherPanel, "Other Panel");

    showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
    backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));

    add(homeContainer);
    cl.show(homeContainer, "Home");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setLocationRelativeTo(null);
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    setTitle("CardLayout Example");
    pack();
    setVisible(true);
}

public static void main(String[] args)
{
    SwingUtilities.invokeLater(MainFrame::new);
}
}

真的很简单,只需调用构造函数并设置可见性即可:

SubFrameClass frame = new SubFrameClass();
frame.setVisible(true);

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM