Невозможно сделать JDialog модальным

Я пытаюсь открыть новый JDialog при нажатии кнопки «Регистрация»..
Но я не могу сделать JDialog модальным..
Я пробовал setModal(true), а также setModalityType(ModalityType.DOCUMENT_MODAL) ; Но не повезло .. (я использую плагин Eclipse WindowBuilder)
P.S: я новичок в JAVA ..
Вот мой код...

import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.xml.ws.handler.MessageContext;


public class loginpage extends JFrame {

    private JPanel contentPane;
    private JTextField userid;
    private JPasswordField password;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    loginpage frame = new loginpage();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public loginpage() {
        super("User Login");
        setResizable(false);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(400, 200, 550, 370);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(null);
        setContentPane(contentPane);

        JLabel label = new JLabel("Please enter your login credentials...");
        label.setFont(new Font("Times New Roman", Font.PLAIN, 25));
        label.setForeground(Color.BLUE);
        label.setBounds(79, 11, 400, 61);
        contentPane.add(label);

        JLabel lblLoginId = new JLabel("User ID :");
        lblLoginId.setFont(new Font("Tahoma", Font.PLAIN, 12));
        lblLoginId.setBounds(159, 142, 71, 17);
        contentPane.add(lblLoginId);

        JLabel lblUserType = new JLabel("User Type :");
        lblUserType.setFont(new Font("Tahoma", Font.PLAIN, 12));
        lblUserType.setBounds(159, 102, 85, 17);
        contentPane.add(lblUserType);

        JLabel lblPassword = new JLabel("Password :");
        lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
        lblPassword.setBounds(159, 188, 96, 14);
        contentPane.add(lblPassword);

        userid = new JTextField();
        userid.setBounds(254, 141, 114, 20);
        contentPane.add(userid);
        userid.setColumns(10);

        password = new JPasswordField();
        password.setBounds(254, 186, 114, 20);
        contentPane.add(password);

        JComboBox usertype = new JComboBox();
        usertype.setBounds(254, 101, 89, 20);
        contentPane.add(usertype);
        usertype.addItem("Admin");
        usertype.addItem("Employee");

        JButton btnLogin = new JButton("Login");
        btnLogin.setBounds(254, 228, 71, 23);
        contentPane.add(btnLogin);

        JLabel lblNewEmployeeRegister = new JLabel("New employee? ");
        lblNewEmployeeRegister.setForeground(Color.RED);
        lblNewEmployeeRegister.setBounds(296, 304, 114, 14);
        contentPane.add(lblNewEmployeeRegister);

        JButton btnRegister = new JButton("Register Here");
        btnRegister.setBounds(398, 301, 126, 20);
        contentPane.add(btnRegister);

        ImageIcon myicon = new ImageIcon("src\\logo.gif");
        JLabel iconlabel = new JLabel(myicon);
        iconlabel.setBounds(0, 233, 103, 99 );
        iconlabel.setIcon(myicon);
        contentPane.add(iconlabel);


        //Adding Listeners to buttons

        //Login Button Listener
        btnLogin.addActionListener(new ActionListener()
        {

            //Making the Connection and registering the Drivers
            @Override
            public void actionPerformed(ActionEvent arg0) {

            }//actionPerformed ends here
        });//Login Button Listener ends here


        //Register Button Listener
        btnRegister.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog jd=new JDialog(loginpage.this,"User Registration");
                jd.setLayout(null);
                jd.setVisible(true); 
                jd.setBounds(400,300, 479, 329);  
                jd.setResizable(false);
                setLocationRelativeTo(loginpage.this);
                jd.setModal(true);

                JLabel lblFillUpThe = new JLabel("Fill up the form to register");
                lblFillUpThe.setForeground(Color.BLUE);
                lblFillUpThe.setFont(new Font("Times New Roman", Font.PLAIN, 25));
                lblFillUpThe.setBounds(93, 11, 400, 61);
                jd.add(lblFillUpThe);

                JLabel lblUserId = new JLabel("Type in a User ID :");
                lblUserId.setFont(new Font("Tahoma", Font.PLAIN, 12));
                lblUserId.setBounds(77, 96, 104, 14);
                jd.add(lblUserId);

                JTextField newid = new JTextField();
                newid.setBounds(236, 94, 122, 20);
                jd.add(newid);
                newid.setColumns(10);

                JLabel lblTypeA = new JLabel("Type in a new Password :");
                lblTypeA.setFont(new Font("Tahoma", Font.PLAIN, 12));
                lblTypeA.setBounds(77, 142, 142, 14);
                jd.add(lblTypeA);

                JPasswordField newpass = new JPasswordField();
                newpass.setBounds(236, 140, 122, 20);
                jd.add(newpass);

                JLabel lblConfirmThePassword = new JLabel("Confirm the Password :");
                lblConfirmThePassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
                lblConfirmThePassword.setBounds(77, 189, 130, 14);
                jd.add(lblConfirmThePassword);

                JPasswordField confpass = new JPasswordField();
                confpass.setBounds(236, 187, 122, 20);
                jd.add(confpass);

                JButton reg = new JButton("Register");
                reg.setBounds(239, 237, 89, 23);
                jd.add(reg);



                reg.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        JOptionPane.showMessageDialog(getParent(), "User Registered Successfully..!!", "Successful",JOptionPane.INFORMATION_MESSAGE);

                    }
                });
            }
        });//Register Button Listener ends here

    }
}

person Soumav    schedule 29.06.2013    source источник


Ответы (1)


Попробуйте сделать диалог модальным ДО того, как попытаетесь сделать его видимым. Вы не можете изменить модальное состояние после того, как диалог станет видимым...

JDialog jd=new JDialog(loginpage.this,"User Registration");
jd.setModal(true);
jd.setLayout(null); // THIS IS A BAD IDEA //
jd.setLocationRelativeTo(null);
// This is somewhat pointless, you've set relative location, but know overridden it...
// You should also be relying on the layout manager and pack to determine the size...
jd.setBounds(400,300, 479, 329); 
jd.setResizable(false);
setLocationRelativeTo(loginpage.this);

// Add you other components

jd.setVisible(true); 
person MadProgrammer    schedule 29.06.2013
comment
Да... Это стало модальным, но теперь JDialog отображается как маленькое окно в левом верхнем углу..!!! :-/ - person Soumav; 29.06.2013
comment
@SoumavaDas Используйте подходящий менеджер компоновки и вызовите pack перед setVisible - person MadProgrammer; 29.06.2013
comment
@MadProgrammer Помимо макета, является ли код логически правильным для создания модального JDialog? - person Soumav; 29.06.2013
comment
@SoumavaDas Лично я бы не стал создавать диалог для каждого нового действия, я бы создал его один раз и использовал повторно. Вы не определяете операцию закрытия по умолчанию. У меня может возникнуть соблазн установить его на DISPOSE_ON_CLOSE, но это я. Кроме того, код как есть не в правильном порядке для создания диалога/фрейма/окна, см. мой пример - person MadProgrammer; 29.06.2013
comment
@MadProgrammer: Чувак... Твое предложение создать отдельный класс, расширяющий jdialog (т.е. создать его один раз), установить setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE) и сделать setVisible(true) в конце сработавшим как шарм... БЛАГОДАРНОСТЬ..!! Большой палец вверх... +1 - person Soumav; 29.06.2013