尝试处理一个 class,它在单击取消按钮时扩展 JXPanel

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

我需要处理一个 class,它在单击 Cancel 按钮时扩展 JXPanel,似乎找不到任何方法。

我有一个 Class A ,有按钮 A 单击按钮 A,Class B 被调用。 Class B 有一个显示所有内容的显示方法,并调用 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;
    }

现在我在 ClassC 中有了取消按钮,单击此 ClassC 我需要关闭 ClassB 的对话框

首选的解决方案是定义某种控制器,您可以将其传递给 class C,它可以用来为某些操作提供通知,例如取消操作。

控制器将负责根据 actions/events

确定它应该做什么

这是Model-View-Controller

的例子

另一种解决方案是允许对话框自己控制取消(和其他相关的用户操作),因为取消并不总是对 class C 有意义,或者您将使用值 class 生成或者你不会,它不应该是 class C 的责任来管理这个(这就是模型的来源)

另一种解决方案是将对话框的引用传递给 class C,但这会在对话框和 class 之间产生紧密耦合,并不必要地公开对话框

另一种解决方案是使用 SwingUtilities.windowForComponent,这将允许您获得对包含 class 的 window 的引用,但这对 class 可能会被使用