0

I've created two jframes main_frame and sub_frame where main_frame holds a jbutton. Now i want that button to open sub_frame in the same frame(main_frame) and set main_frame disable until sub_frame is opened. Note that I dont want main_frame to setVisible(false).

2 Answers2

0

I suggest you use a CardLayout

Instead of multiple JFrames, you have multiple JPanels and switch between them.

Here is an example:

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);
}
}
Jonah
  • 1,013
  • 15
  • 25
0

It is really easy, just call the constructor and set visibility:

SubFrameClass frame = new SubFrameClass();
frame.setVisible(true);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97