Hy,
I have a JFrame main window and a Dialog window, how can i use the method setPositionRelativeTo() so that my Dialog window positions centered on the main window ?
Thanks

If you pass the JFrame reference as the "owner" parameter to the JDialog constructor it will center on it. Example:

JFrame frame = new JFrame();
        frame.setBounds(200,200,300, 400);
        frame.setVisible(true);
        
        JDialog dialog = new JDialog(frame,"test");
        dialog.setVisible(true);

my Dialog class is used inside the main window class, so i`m using "this" in Dialog`s object constructor, but the Dialog window is not centered;
please let me know if you want to post the code

my Dialog class is used inside the main window class, so i`m using "this" in Dialog`s object constructor, but the Dialog window is not centered;
please let me know if you want to post the code

Yes, the code would probably help. If your main window class extends JFrame and is valid and visible when the JDialog is shown, then using "this" for the owner should be all that is needed.

The Dialog class - 231(see the 1st constructor)
the dialog window is created at line 210

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.io.DataInputStream;
import java.lang.*;
import java.lang.String;


public class MyMain extends JFrame implements ActionListener, TextListener{
	static String in = "  ", aux = "", uChar = "", uChar2 = "";
	public static String cuvant = "";
	public static String cuvant2 = "";
	public static String raspuns = "no";
	static int v[]; //contine 0-litera neintoarsa si 1-litera intoarsa
	static int nrLinii, s;
	static int gen = 0;
	public static int pas = 6;//vietzi
	static char c;
	static int nrJocT = 0;
	public AskWindow askW;
	
	boolean ok, ok2;
	static JLabel j, j2, j3;
	TextField t;
	JPanel p1, x, y;
	static JPanel p2;
	JButton b;
	Image img;
	static DrawingPanel drawing_panel;
	public MyMain(String titlu) {
		super(titlu);
		setSize(220, 320);
		// MetodasetLayoutnuseaplicadirectferestrei
		getContentPane().setLayout(new BorderLayout());
		// ComponenteleaudenumiriceincepculiteraJ
		// TextulpoatefisiinformatHTML
		b = new JButton("Cauta");
		b.setEnabled(false);
		b.addActionListener(this);
		
		img = Toolkit.getDefaultToolkit().getImage("Hangman-0 (192 x 192).png");
		drawing_panel =  new DrawingPanel (img);
		
		p2 = new JPanel();
		j = new JLabel("");
		j2 = new JLabel("");
		j3 = new JLabel("");
		j.setHorizontalAlignment(SwingConstants.CENTER);
		j2.setHorizontalAlignment(SwingConstants.CENTER);
		j3.setHorizontalAlignment(SwingConstants.CENTER);
		p2.setLayout(new BorderLayout());
		p2.add(drawing_panel, BorderLayout.CENTER);
		p2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		//p2.setSize(300, 200);
		p1 = new JPanel();
		p1.setLayout(new FlowLayout());
		p2.setPreferredSize(new Dimension(220, 200));
		p1.setPreferredSize(new Dimension(220, 100));
		t = new TextField(1);
		t.addTextListener(this);
		x = new JPanel();
		y = new JPanel();
		x.setLayout(new BorderLayout());
		y.setLayout(new FlowLayout());
		x.add(j, BorderLayout.NORTH);
		x.add(j2, BorderLayout.CENTER);
		x.add(j3, BorderLayout.SOUTH);
		y.add(t);
		y.add(b);
		p1.add(y, BorderLayout.NORTH);
		p1.add(x, BorderLayout.SOUTH);
		p1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		getContentPane().add(p1, BorderLayout.SOUTH);
		getContentPane().add(p2, BorderLayout.CENTER);
		pack();
		//setSize(220,300);
		this.setLocation(50, 50);
		rep();
		//afisNrJocT();
		
		
	}
	
	public static void rep(){
			cuvant2 = "";
			pas = 6;
			getWord();
			for (int i=0;i<cuvant.length();i++)
				if(v[i] == 1)
					cuvant2 += cuvant.charAt(i) + " ";
				else
					cuvant2 += "_ ";
			j.setText(cuvant2);
			j2.setText("");
			j3.setText("Introduceti o litera");
		
	}
	public void afisNrJocT(){
		askW = new AskWindow(this, false);
	}
	
	public void textValueChanged(TextEvent e){
		in = t.getText();
		if (in.length() != 0){
		do{
			if((in.charAt(0) < 65) || (in.charAt(0) > 122))
				t.setText("");
				in = t.getText();
		}
		while(in.length()!=0 && (in.charAt(0) < 65 || in.charAt(0) > 122) );//sa fie litera
		b.setEnabled(true);}
		else
			b.setEnabled(false);
		if (in.length() > 1){	
			t.setText("" + in.charAt(0));
			t.setCaretPosition(5);
		}
	}
	
	private static void getWord() {
		try {// numarare cuvinte din fisier(un cuvant/linie)
			FileInputStream input = new FileInputStream("cuvinte.txt");
			DataInputStream dIn = new DataInputStream(input);
			while ((aux = dIn.readLine()) != null) {
				nrLinii++;
			}
		} catch (Exception e) {
			System.err.println("nu pot citi din fish1");
		}
		
		gen = (int)(Math.random()*nrLinii+1);//numar random pt alegerea random a cuv din fisier
		int nrL = 0;
		s = 0;
		try{//citire aleatoare a unui cuvant din fisier
			FileInputStream input = new FileInputStream("cuvinte.txt");
			DataInputStream dIn = new DataInputStream(input);
			while ((aux = dIn.readLine())!=null){
				nrL++;
				if (gen == nrL){
					cuvant ="";
					cuvant += aux;
				}
			}
		}
		catch(Exception e){
			System.err.println("nu pot citi din fish2");}
		v = new int[cuvant.length()];
		for (int i=1; i<cuvant.length()-1;i++){v[i] = 0;}
		v[0] = 1;
		for (int i=1;i < cuvant.length()-1;i++)//afisare primei si ultimei litere, precum si a celor din interiorul cuvantului similare cu acestea
			if(cuvant.charAt(0) == cuvant.charAt(i) || (i!=cuvant.length()-1 && cuvant.charAt(cuvant.length()-1) == cuvant.charAt(i)))
				v[i] = 1;
		v[cuvant.length()-1] = 1;
		
		for (int i=0; i < cuvant.length(); i++){//calcularea nr de litere nedescoperite
			if (v[i] == 0)
				s++;
		}
	}
	
	public void actionPerformed(ActionEvent e){
		t.setText("");
		t.requestFocusInWindow();
		ok = false;
		for (int i=0; i<cuvant.length();i++){
			if(cuvant.charAt(i)
					== Character.toLowerCase(in.charAt(0))) {//daca litera citita este in cuvant
				if(v[i] != 1){//daca e nedescoperita
					v[i] = 1;//se descopera
					s--;//scade nru de lit nedescoperite
				}//daca era deja descoperita, nu tbia ca 's' sa scada
				ok = true;//litera gasita
			}
		}
		if(ok == false){//litera negasita
			
			ok2 = false;
				for (int i=0; i<uChar.length(); i++)
					if (uChar.charAt(i) == Character.toLowerCase(in.charAt(0)))
						ok2 = true;
					
				if(ok2 == false){
					uChar += in.toLowerCase();//se adauga la vectorul de litere negasite
					pas--;
					drawing_panel = null;
					drawing_panel = new DrawingPanel(Toolkit.getDefaultToolkit().getImage("Hangman-" +(6-pas)+ " (192 x 192).png"));
					p2.add(drawing_panel, BorderLayout.CENTER);
			}
		}
		cuvant2 = "";
		for (int i=0; i<cuvant.length();i++){//afisarea cuvantului actualizat
			if(v[i] == 0)
				cuvant2 += ("_ ");
			else
				cuvant2 += cuvant.charAt(i) + " ";
		}
		if (pas == 0){afisNrJocT();}
		
		j.setText(cuvant2);
		//for (int j = 0;j < uChar.length();j++)//afisare litere negasite
			j2.setText(uChar);
			if(s == 0){ 
				j3.setText("joc terminat");
				nrJocT++;
				askW = new AskWindow(this, "Continuati jocul?", true);
			}	
			else
				j3.setText("Mai ai "+pas+" pasi pana la moarte!");
			
		
	}
	public static void main(String args[]){
		MyMain f;
		f = new MyMain("test");
		f.addWindowListener (new WindowAdapter () {
            public void windowClosing (WindowEvent event)
            {
                System.exit (0);
            }
        });
		f.show();
		
		
	}

public class AskWindow extends Dialog implements ActionListener{
	private TextField text;
	private Button ok, ko, cancel;
		
	public AskWindow(Frame parinte, String titlu, boolean modala){
		super(parinte, titlu, modala);
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				MyMain.raspuns = null;
				dispose();
				}
		});
		
		Panel panel = new Panel();
		ok = new Button("OK");
		cancel = new Button("Cancel");
		panel.add(ok);
		panel.add(cancel);
		add(panel,BorderLayout.SOUTH);
		pack();
		ok.addActionListener(this);
		cancel.addActionListener(this);
		show();
		}
	public AskWindow(Frame parinte, boolean modala){
		super(parinte, modala);
		JLabel l;
		int t = 5;
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				MyMain.raspuns = null;
				dispose();
				}
		});
		Panel panel = new Panel();
		ko = new Button("OK");
		l = new JLabel();
		l.setText("ati castigat de "+ nrJocT + " ori");
		panel.add(l);
		panel.add(ko);
		add(panel, BorderLayout.SOUTH);
		pack();
		ko.addActionListener(this);
		show();
		for (int i=0; i < t; i++)
		{
			ko.setLabel("" + (t-i));
			try{
				Thread.sleep(1000);
			}
			catch(InterruptedException o){}
		}

	}
		
	public void actionPerformed(ActionEvent e){
		Object sursa = e.getSource();
		int t = 5;
		if (sursa == ok){
			MyMain.raspuns = "yes";
			MyMain.rep();
			dispose();
		}
		else
			if (sursa == cancel){
			MyMain.raspuns = "no";
			dispose();
			afisNrJocT();
			}
			else
				System.exit(0);
		
		}
	
	}

	class DrawingPanel extends JPanel {
		Image img;

		DrawingPanel(Image img) {
			this.img = img;
		}

		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.drawImage(img, 5, 5, this);

		} 

	}
}

The dialog is centered in the frame when I click the button. Where is it appearing for you?

Well, after finding this bug report http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4102292 I tried running your app on the oldest JDK I have here, 1.4.2, and it still functions fine for me. The dialog is always centered in the frame. Are you running this in Windows or some other OS? I'm at a loss as to the cause if you are using Windows and a recent JDK.

Have you tried adding

setLocationRelativeTo(parinte);

after the super() call or before show() in your dialog constructor already? You mentioned the method in your original post but not whether you had used it.

I`m using Windows XP and JDK 1.6.0_02

it almost worked with setLocationRelativeTo(parinte) except that it isn`t exactly in the center, the top bottom corner of the dialog window is exactly on the center of the main window; earlier i tried to use that function, but i`ve made a mistake, i`ve used the "this" argument, my mistake, i`m a newbie in Java; thanks 4 your help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.