powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / JDialog
8 сообщений из 8, страница 1 из 1
JDialog
    #33266806
GlukOza
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Есть фрейм. В нем я вывожу диалоговое окно.

Как вывести фрейм в центр экрана я знаю. А как JDialog вывести в центр фрейма?

Не получается...Окно JDialog выводится в позицию с координатами (0;0).
...
Рейтинг: 0 / 0
JDialog
    #33266817
Naug
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
зависит от испольpeго layout-а. Юзай BorderLayout.
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
...
Рейтинг: 0 / 0
JDialog
    #33266837
wessen
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Naugзависит от испольpeго layout-а. Юзай BorderLayout.
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html

а чего, правда, что положение диалога над окном, зависит от layout'a родительского окна ? :)
...
Рейтинг: 0 / 0
JDialog
    #33266855
Naug
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Может и нет. Может я что такое JDialog не знаю
...
Рейтинг: 0 / 0
JDialog
    #33266862
GlukOza
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Naugзависит от испольpeго layout-а. Юзай BorderLayout.
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
 import  javax.swing.*;
 import  java.awt.event.ActionListener;
 import  java.awt.event.WindowAdapter;
 import  java.awt.event.WindowEvent;
 import  java.awt.event.ActionEvent;
 import  java.awt.*;

 public   class  ConnectPererach
{
     public   static   void  main(String[] args)
    {
        ConnectPererachFrame frame =  new  ConnectPererachFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.show();
    }
}

 class  ConnectPererachFrame  extends  JFrame
{
     public  ConnectPererachFrame()
    {
        setTitle(" Вхід ");
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension screenSize = kit.getScreenSize();
         int  screenHeight = screenSize.height;
         int  screenWidth = screenSize.width;

        setSize(screenWidth / 2 , screenHeight/ 2 );
        setLocation(screenWidth/ 4 , screenHeight/ 4 );

        addWindowListener( new  WindowAdapter()
        {
             public   void  windowClosing(WindowEvent e)
            {
                System.exit( 0 );
            }
        });

        JMenuBar mbar =  new  JMenuBar();
        setJMenuBar(mbar);
        JMenu fileMenu =  new  JMenu("Файл");
        mbar.add(fileMenu);

        connectItem =  new  JMenuItem("Логін");
        connectItem.addActionListener( new  ConnectAction());
        fileMenu.add(connectItem);

        exitItem =  new  JMenuItem("Вихід");
        exitItem.addActionListener( new  ActionListener()
        {
             public   void  actionPerformed(ActionEvent event)
            {
                System.exit( 0 );
            }
        });
        fileMenu.add(exitItem);
        textArea =  new  JTextArea();
    }

     private  PasswordChooser dialog =  null ;
     private  JMenuItem connectItem;
     private  JMenuItem exitItem;
     private  JTextArea textArea;

     private   class  ConnectAction  implements  ActionListener
    {
         public   void  actionPerformed(ActionEvent event)
        {
             if  (dialog  ==  null )
                dialog =  new  PasswordChooser();
            dialog.setUser( new  User("u016", null ));
        
             if  (dialog.showDialog(ConnectPererachFrame. this ,"Вхід у систему"));
            {
                User u = dialog.getUser();
            }
        }
    }
}

 class  PasswordChooser  extends  JPanel
{
     public  PasswordChooser()
    {
        setLayout( new  BorderLayout());
        
        JPanel panel =  new  JPanel();
        panel.setLayout( new  GridLayout( 2 ,  2 ));
        panel.add( new  JLabel("Мережеве ім'я:"));
        panel.add(username =  new  JTextField(""));
        panel.add( new  JLabel("Пароль:"));
        panel.add(password =  new  JPasswordField(""));
        add(panel,BorderLayout.CENTER);

        okButton =  new  JButton("Підтвердити");
        okButton.addActionListener( new  ActionListener()
        {
             public   void  actionPerformed(ActionEvent avent)
            {
                ok = true;
                dialog.setVisible(false);
            }
        });

        cancelButton =  new  JButton("Відмовитись");
        cancelButton.addActionListener( new  ActionListener()
        {
             public   void  actionPerformed(ActionEvent event)
            {
                dialog.setVisible(false);
            }
        });

        JPanel buttonPanel =  new  JPanel();
        buttonPanel.add(okButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel, BorderLayout.SOUTH);

   }

    public   void  setUser(User u)
   {
       username.setText(u.getName());
   }


    public  User getUser()
   {
        return   new  User(username.getText(),password.getPassword());
   }

    public   boolean  showDialog(Component parent, String title)
   {
       ok = false;

       Frame owner =  null ;
        if  (parent  instanceof  Frame)
           owner = (Frame) parent;
        else 
           owner = (Frame)SwingUtilities.getAncestorOfClass(Frame. class , parent);

        if  (dialog ==  null  || dialog.getOwner() != owner)
       {
           dialog =  new  JDialog(owner, true);
           dialog.getContentPane().add( this );
           dialog.pack();
       }

       dialog.setTitle(title);
       dialog.show();
        return  ok;
   }

     private  JTextField username;
     private  JPasswordField password;
     private   boolean  ok;
     private  JButton okButton;
     private  JButton cancelButton;
     private  JDialog dialog;
}

 class  User
{
     public  User(String aName,  char [] aPassword)
    {
        name = aName;
        password = aPassword;
    }

     public  String getName() { return  name;}
     public   char [] getPassword() { return  password;}

     public   void  setName(String aName) { name = aName;}
     public   void  setPassword( char [] aPassword) { password = aPassword;}

     private  String name;
     private   char [] password;
}
...
Рейтинг: 0 / 0
JDialog
    #33266884
GMax
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
авторsetBounds
public void setBounds(int x,
int y,
int width,
int height)Description copied from class: Component
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height.

Overrides:
setBounds in class Component
Parameters:
x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component

Например с помощью этого метода. Т. е. получаешь положение и размеры своего фрейма. Далее берешь размер своего диалога, ну и высчитываешь и задаешь положение и размер диалога.
В общем смотри класс java.awt.Window и ищи нужные тебе методы.
...
Рейтинг: 0 / 0
JDialog
    #33266994
GlukOza
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
GMax авторsetBounds
public void setBounds(int x,
int y,
int width,
int height)Description copied from class: Component
Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height.

Overrides:
setBounds in class Component
Parameters:
x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component

Например с помощью этого метода. Т. е. получаешь положение и размеры своего фрейма. Далее берешь размер своего диалога, ну и высчитываешь и задаешь положение и размер диалога.
В общем смотри класс java.awt.Window и ищи нужные тебе методы.


Спасибо за идею. Вот что получилось:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
  public   boolean  showDialog(Component parent, String title)
   {
       ok = false;

       Frame owner =  null ;
        if  (parent  instanceof  Frame)
           owner = (Frame) parent;
        else 
           owner = (Frame)SwingUtilities.getAncestorOfClass(Frame. class , parent);

        if  (dialog ==  null  || dialog.getOwner() != owner)
       {
           dialog =  new  JDialog(owner, true);
           setLayout( new  GridLayout( 2 ,  2 ));
           dialog.getContentPane().add( this ,BorderLayout.CENTER);
           dialog.pack();
       }

       dialog.setTitle(title);
       Rectangle gg = owner.getBounds();
        int  x = ( int ) gg.getX();
        int  y = ( int ) gg.getY();
        int  height = ( int ) gg.getHeight();
        int  width = ( int ) gg.getWidth();

       dialog.setLocation(x+height/ 4 , y+width/ 4 );
       dialog.show();
        return  ok;
   }
...
Рейтинг: 0 / 0
JDialog
    #33268837
GlukOza
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
В коде, приведенном выше, мне надо выудить значение поля password.
Код: plaintext
 char [] pass = password.getPassword();

дает пробелы.

Подскажите как мне правильно взять данные из поля JPasswordField?
...
Рейтинг: 0 / 0
8 сообщений из 8, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / JDialog
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]