簡體   English   中英

如何從父對話框Java Swing中刪除子jdialog參考

[英]How to remove child jdialog reference from the parent dialog Java Swing

我想從父對話框中刪除子對話框,而無需單擊子對話框 並且無需編輯父對話框即可創建源代碼。 父對話框正在重用,並且只創建一次。

我希望這是您的答案:

package stack;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DialogShower implements WindowListener {

  JFrame frame;
  JButton showButton;
  ParentDialog parentDialog;
  boolean fristTimeOpen = true;

  public DialogShower() {
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    parentDialog = new ParentDialog();
    parentDialog.addWindowListener(this);

    showButton = new JButton("Show me");
    showButton.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        if (fristTimeOpen) {
          parentDialog.childDialog.setVisible(true);
        }
        parentDialog.setVisible(true);
      }
    });

    frame.getContentPane().add(showButton);
    frame.setSize(100, 100);
    frame.setVisible(true);
  }

  public class ParentDialog extends JDialog {

    ChildDialog childDialog;

    public ParentDialog() {
      super(frame, "ParentDialog", true);
      childDialog = new ChildDialog();
    }

    public class ChildDialog extends JDialog {

      JLabel label;

      public ChildDialog() {
        super(ParentDialog.this, "childDailg", false);
        label = new JLabel("Notification : Dialog");
        getContentPane().add(label);
        setLocation(300, 300);
      }
    }
  }

  @Override
  public void windowActivated(WindowEvent e) {
  }

  @Override
  public void windowClosed(WindowEvent e) {
    System.out.println("2");
  }

  @Override
  public void windowClosing(WindowEvent e) {
    fristTimeOpen = false;
    parentDialog.childDialog.dispose();
  }

  @Override
  public void windowDeactivated(WindowEvent e) {
  }

  @Override
  public void windowDeiconified(WindowEvent e) {
  }

  @Override
  public void windowIconified(WindowEvent e) {
  }

  @Override
  public void windowOpened(WindowEvent e) {
  }

  public static void main(String[] args) {
    new DialogShower();
  }
}

當您單擊“ Show me它打開父對話框以及子對話框”按鈕時,我創建了兩個對話框。 當您關閉父對話框時,它會自動關閉子對話框。 我使用WindowListener在父對話框關閉時執行操作。再次打開父對話框時,它不會打開子對話框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM