Search code examples
javaswingpanels

Controlling another class from a different class


I am having a bit of problem regarding Swing. I have a JFrame called FrameMain. Inside it is a JPanel called panelChoices.

When FrameMain is called/created, it fills up the panelChoices object with a number of PanelEntries objects, which is a JPanel with a number of JButtons in it (it is a different class that I wrote).

What I want to do is when I click one of the buttons inside the PanelEntries object, I want to destroy/remove FrameMain, along with the rest of it components (including the PanelEntries object that contains the JButton).

I've tried using super but it returns the JPanel (the PanelEntries object) that holds the JButton and not FrameMain that holds them all together. How can I achieve this?

EDIT: It seems that I am not clear enough, so here's a bit more information from my work. I don't have the actual code right now because I am on a different machine but I hope this will help elaborate my question.

public class FrameMain() {
    private JFrame frameMain;
    private JPanel panelChoices;

    public FrameMain(args) {
        createGUI();
        loadData();
    }

    private void createGUI() {
        JFrame frameMain = new JFrame();
        JPanel panelChoices = new JPanel(new GridLayout(1,1));
        frameMain.add(panel);
        // removed formatting and other design codes since they are not important.
        pack();
    }

    private void loadData() {
        boolean available;
        for (int i = 1; i <= 10; i++) {
            // do some if/else and give value to boolean available
            PanelEntries panel = new PanelEntries(i, available);
            frameMain.add(panel);
            // more code here to handle data.
        }
    }
}

public class PanelEntries() extends JPanel {

    public PanelEntries(int num, boolean avb) {
        JButton button = new JButton("Button Number " + num);
        button.setEnabled(avb);
        add(button);
        // add action listener to created button so that it calls 'nextScreen()' when clicked.
        // more code
        pack();
    }

    private void nextScreen() {
        // destroy/dispose MainFrame here.
        // See Notes.
        AnotherFrame anotherFrame = new AnotherFrame();
    }
}

Notes:

  1. All classes are inside their own .java file.
  2. I need to know how to dispose FrameMain from the button inside the PanelEntries object, not just disposing a JFrame.

Solution

  • As per the given information,

    1. If you want to exit the application, its not a big deal use System.exit(0); :)

    2. If you mean to dispose the frame, jframe.dispose();

    3. If you want to remove a componet / all components you can use .remove(Component) / .removeAll() etc

    If this did not help, please re-write your question with more information.