Java JDialog create dialog

Description

Java JDialog create dialog

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class Main {
  public static void main(String[] args) {
    JFrame parent = new JFrame();
    JDialog  LOGIN_DIALOG = new MyDialog(parent);

    LOGIN_DIALOG.pack();//w w  w  .  j a  v  a 2  s .  co m
    
    // center dialog
    Dimension scrnSize = Toolkit.getDefaultToolkit().getScreenSize();
    int scrnWidth = LOGIN_DIALOG.getSize().width;
    int scrnHeight = LOGIN_DIALOG.getSize().height;
    int x = (scrnSize.width - scrnWidth) / 2;
    int y = (scrnSize.height - scrnHeight) / 2;

    // Move the window
    LOGIN_DIALOG.setLocation(x, y);
    LOGIN_DIALOG.setResizable(false);
    LOGIN_DIALOG.setVisible(true);
  }
}

class MyDialog extends JDialog {

  public MyDialog(Frame owner) {
    super(owner, true);
    GridLayout cglayout = new GridLayout(3, 3, 10, 10);

    setLayout(cglayout);

    JLabel userNameLbl = new JLabel("User Name: ");
    add(userNameLbl);

    final JTextField userNameFld = new JTextField("Admin", 20);
    add(userNameFld);
    JLabel passwordLbl = new JLabel("Password: ");
    add(passwordLbl);


    final JPasswordField passwordFld = new JPasswordField("drowssap", 20);
    add(passwordFld);

    JButton login = new JButton("Change");
    add(login);
    JButton cancel = new JButton("Cancel");
    add(cancel);
    
    final JDialog dialog = this;
    login.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        dialog.setVisible(false);
        dialog.dispose();
      }
    });
  }
}



PreviousNext

Related