user2176576
user2176576

Reputation: 756

Trying to dispose a class which extends JXPanel on click of Cancel Button

I need to dispose a class which extends JXPanel on click of a Cancel button, cant seem to find any method for that.

I have a Class A ,having button A on click on button A, Class B is getting called. Class B has a display method which displays everything, and calls ClassC

class A : in actionPerformed() 
if (e.getSource().equals(buttonA )){
            try {
                new ClassB(parent);
            } catch (BusinessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

In class B


private void display() throws BusinessException{
        dialog = new JDialog(parent, "Dialog");
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setContentPane(createContentPane());
        dialog.setModal(true);
        //dialog.setBackground(Color.WHITE);
        dialog.setMinimumSize(new Dimension(1190, 200));
        //dialog.setMaximumSize(new Dimension(1190, 500));
        dialog.pack();
        dialog.setLocationRelativeTo(parent);
        dialog.setVisible(true);
    }

in createContentPane() 

    public JPanel createContentPanel() throws BusinessException{
        JPanel panel = new JPanel(new CardLayout());
        panel.setBackground(Color.WHITE);

        panel.add("New Dialog", new ClassC(parent));

        return panel;
    }

Now I have my Cancel Button in ClassC ,on click of this Class C I need to close ClassB's dialog

Upvotes: 0

Views: 58

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

The preferred solution would be to define some kind of controller which you could pass to class C, which it could use to provide notification over certain actions, like the cancel action for example.

The controller would the be responsible for determining what it should do based on the actions/events

This is an example of Model-View-Controller

Another solution would be to allow the dialog to control the cancel (and other related user actions) itself, as Cancel doesn't always have meaning for class C, either you will use the values the class generates or you won't, it shouldn't be class C's responsibility to manage this (that's where the model comes in)

Another solution would be to pass a reference of the dialog to class C, but this produces a tight coupling between the dialog and the class and exposes the dialog unnecessarily

Another solution would be to use SwingUtilities.windowForComponent, which would allow you to obtain a reference to the window which contains the class, but this makes assumptions about how the class might be used

Upvotes: 2

Related Questions