我创建了两个jframes main_frame和sub_frame,其中main_frame包含一个jbutton。现在我希望该按钮在同一帧(main_frame)中打开sub_frame并设置main_frame disable,直到打开sub_frame。 请注意,我不希望main_frame为setVisible(false)。
答案 0 :(得分:0)
我建议您使用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);
}
}
答案 1 :(得分:0)
这很简单,只需调用构造函数并设置可见性:
SubFrameClass frame = new SubFrameClass();
frame.setVisible(true);