Java Swing How to - Create JDialog with button and MouseListener








Question

We would like to know how to create JDialog with button and MouseListener.

Answer

/*from w  w  w  . ja  va 2 s. co  m*/
import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);

    JDialog dialog = new JDialog(frame, "Dialog", true);

    JPanel mainGui = new JPanel(new BorderLayout());
    mainGui.setBorder(new EmptyBorder(20, 20, 20, 20));
    mainGui.add(new JLabel("Contents go here"), BorderLayout.CENTER);

    JPanel buttonPanel = new JPanel(new FlowLayout());
    mainGui.add(buttonPanel, BorderLayout.SOUTH);

    JButton close = new JButton("Close");
    close.addActionListener(e->dialog.setVisible(false));

    buttonPanel.add(close);

    frame.setVisible(true);

    dialog.setContentPane(mainGui);
    dialog.pack();
    dialog.setVisible(true);
  }
}