Centralizar Jframe!

21 respostas
K

salve galera!!!

to com um probleminha aqui:

sou iniciante em java e preciso centralizar a janela da minha aplicação...

já utilizei alguns métodos que vi aqui no fórum porém não consegui fazer nenhum funcionar.

Vou postar o código para ver se vcs podem me ajudar com alguma solução:

estou usando o Visual Editor!!

public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (Exception e) {

		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				principal thisClass = new principal();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	public principal() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
	   	this.setSize(800,600);
		this.setContentPane(getJContentPane());
		this.setJMenuBar(getMenuPrincipal());
		this.setTitle("CalcDist");
		this.setResizable(false);
	}

valew abraço!

21 Respostas

W

coloca esse codigo antes do setVisible(true);

Dimension paneSize = this.getSize();

Dimension screenSize = this.getToolkit().getScreenSize();

setLocation( (screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
R

Nao tenho tanta experiencia mas
vc pode tentar fazer algo como :

Toolkit kit = Toolkit.getDefaultToolkit();
        
        int width = ((kit.getScreenSize().width  / 2) - (this.getWidth() / 2));
        int height = ((kit.getScreenSize().height / 2) - (this.getHeight() / 2));
        
        this.setLocation(width,height);
K

windsofhell, raphaelfs

tentei os dois métodos porém não funcionou…

não sei se sou eu q não estou colocando o código no local certo ou se tem a ver com o visual Editor!!

se puderem colocar o método no local certo do código para eu ver como fica agradeço!!

valew!!

R

A sua classe faz extends de JFrame?

Se a resposta for sim… coloque o codigo dentro de initialize() e faça os Import’s necessarios

R

Para centralizar um JFrame ou uma JDialog utilize:

frame.setLocationRelativeTo(null);
S

Acho que desta forma funciona …

int width = (this.getWidth() / 4) ;
int height = (this.getHeight() / 4)
setLocation(width, height);
K
raphaelfs:
A sua classe faz extends de JFrame?

Se a resposta for sim... coloque o codigo dentro de initialize() e faça os Import's necessarios

a resposta é sim ehuehue

public class principal extends JFrame implements ActionListener 
.
.
.
.{

vou mandar o código do jeito que vc falou.. tentei rodar e a bendita janela num foi pro meio da tela aheuaiehau

public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (Exception e) {

		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				principal thisClass = new principal();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	public principal() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
	    this.setSize(800,600);
	    Toolkit kit = Toolkit.getDefaultToolkit();  
	       
	    int width = ((kit.getScreenSize().width  / 2) - (this.getWidth() / 2));  
	    int height = ((kit.getScreenSize().height / 2) - (this.getHeight() / 2));  
	      
	    this.setLocation(width,height);  
	    this.setContentPane(getJContentPane());
	    this.setJMenuBar(getMenuPrincipal());
	    this.setTitle("CalcDist");
	    this.setResizable(false);
	}
	

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.setBackground(new Color(136, 158, 180));
			jContentPane.add(getCalculadora());
			jContentPane.add(getMenuArquivo(), null);
		}
		return jContentPane;
	}

mais uma coisa:

li em alguns tópicos sobre o método setLocationRelativeTo...

onde chamaria este método?????

valew moçada!!

K
RicardoLuis:
Para centralizar um JFrame ou uma JDialog utilize:
frame.setLocationRelativeTo(null);

cara ve se eu fiz certo.. por q eu tentei e tb num deu certo aehuaiehaueha

public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (Exception e) {

		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				principal thisClass = new principal();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
				thisClass.setLocationRelativeTo(null); 
			}
		});
	}

Eu sou brasileiro e num desisto nunca!! aehaiuehaui

S

Como está a sua class Principal ?

K
sfing:
Como está a sua class Principal ?

cara minha classe ta um poco grande... mas vou postar uma parte...

public class principal extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private DecimalFormat dff = new DecimalFormat("0.0000"); // @jve:decl-index=0:

	private JPanel jContentPane = null;

	private JTabbedPane calculadora = null;

	private JPanel painelNormal = null;

private JTabbedPane getCalculadora() {
		if (calculadora == null) {
			calculadora = new JTabbedPane();
			calculadora.setBounds(392, 276, 378, 263);
			calculadora.setBackground(Color.lightGray);
			calculadora.setTabPlacement(JTabbedPane.TOP);
			calculadora.addTab("                Normal          ",
					getPainelNormal());
			calculadora.addTab("             Exponencial            ",
					getPainelExponencial());
			calculadora.addTab(" Binomial ", getPainelBinomial());
			calculadora
					.addTab("Binomial Negativa", getPainelBinomialNegativa());
			calculadora.addTab("Geométrica", getPainelGeometrica());
			calculadora.addTab("   Poisson   ", getPainelPoisson());
		}
		return calculadora;
	}

	/**
	 * This method initializes painelNormal
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getPainelNormal() {
		if (painelNormal == null) {
			xentre = new JLabel(new ImageIcon("xentre.gif"));
			xentre.setBounds(265, 21, 50, 45);
			xmaior = new JLabel(new ImageIcon("xmaior.gif"));
			xmaior.setBounds(158, 21, 50, 45);
			xmenor = new JLabel(new ImageIcon("xmenor.gif"));
			xmenor.setBounds(47, 22, 50, 45);
			painelNormal = new JPanel();
			painelNormal.setLayout(null);
			painelNormal.setBackground(Color.lightGray);
			normalGroup = new ButtonGroup();
			normalGroup.add(getNormal1());
			normalGroup.add(getNormal2());
			normalGroup.add(getNormal3());
			painelNormal.add(getNormal1());
			painelNormal.add(getNormal2());
			painelNormal.add(getNormal3());
			painelNormal.add(xmenor);
			painelNormal.add(xmaior);
			painelNormal.add(xentre);
			painelNormal.add(getCardlayout());
			painelNormal.add(getBotaoAjuda());
		}
		return painelNormal;
	}

public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (Exception e) {

		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				principal thisClass = new principal();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
				
			}
		});
	}

	public principal() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
	   	this.setSize(800,600);
	   	this.setContentPane(getJContentPane());
		this.setJMenuBar(getMenuPrincipal());
		this.setTitle("CalcDist");
		this.setResizable(false);
	}
	

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.setBackground(new Color(136, 158, 180));
			jContentPane.add(getCalculadora());
			jContentPane.add(getMenuArquivo(), null);
		}
		return jContentPane;
	}
}
R

Tenta fazer:

public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (Exception e) {

		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				principal thisClass = new principal();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				
                                Toolkit kit = Toolkit.getDefaultToolkit();
                                int width = ((kit.getScreenSize().width  / 2) - (this.getWidth() / 2));
                                int height = ((kit.getScreenSize().height / 2) - (this.getHeight() / 2));
                                thisClass.setLocation(width,height);   


                                thisClass.setVisible(true);
				thisClass.setLocationRelativeTo(null); 
			}
		});
R

Desculpe … tire o

thisClass.setLocationRelativeTo(null);

S
private void initialize() {  
         this.setSize(800,600);  
         this.setContentPane(getJContentPane());  
         this.setJMenuBar(getMenuPrincipal());  
         this.setTitle("CalcDist");  
         this.setResizable(false);  
}

Faz assim …

private void initialize() {  
int width = (this.getWidth() / 4) ;  
int height = (this.getHeight() / 4) 

this.setBounds(800,600,width,height  );  
this.setContentPane(getJContentPane());  
this.setJMenuBar(getMenuPrincipal());  
this.setTitle("CalcDist");  
this.setResizable(false);  
this.setVisible(true);
}
K

raphaelfs

o Eclipse não aceita essas duas linhas

int width = ((kit.getScreenSize().width / 2) - (this.getWidth() / 2)); int height = ((kit.getScreenSize().height / 2) - (this.getHeight() / 2));

ele não reconhece os métodos this.getWidth(), this.getHeight()

tem idéia do que possa ser??

valew cara!!

S

Os métodos this.getWidth(), this.getHeight() são reconhecidos dentro do construtor de um JFrame … isso se não me engano !

R

foi mal… coloca

int width = ((kit.getScreenSize().width  / 2) - (thisClass.getWidth() / 2));  
int height = ((kit.getScreenSize().height / 2) - (thisClass.getHeight() / 2));
K

tb tentei e naum deu…

to achando q é o visual editor o culpado!!

K
raphaelfs:
foi mal... coloca
int width = ((kit.getScreenSize().width  / 2) - (thisClass.getWidth() / 2));  
int height = ((kit.getScreenSize().height / 2) - (thisClass.getHeight() / 2));
public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager
					.getCrossPlatformLookAndFeelClassName());
		} catch (Exception e) {

		}
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				principal thisClass = new principal();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				Toolkit kit = Toolkit.getDefaultToolkit();  
				int width = ((kit.getScreenSize().width  / 2) - (thisClass.getWidth() / 2));  
				int height = ((kit.getScreenSize().height / 2) - (thisClass.getHeight() / 2));  
				thisClass.setLocation(width,height);     
				thisClass.setVisible(true);  
				
			}

		});
	}

	public principal() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	   private void initialize() {    
		   this.setSize(800,600);    
		   this.setContentPane(getJContentPane());    
		   this.setJMenuBar(getMenuPrincipal());    
		   this.setTitle("CalcDist");    
		   this.setResizable(false);    
		    
	   }

tb naum deu certo!! :cry:

ta muito estranho!!! to achando q é por causa do Visual Editor!!!

vo larga mão o usuário que arraste a janela!!! aheuiaheuiaheuiahea

R

Coloque a chamada a setLocationRelativeTo(null) no final do seu método initialize que irá funcionar.

S

Faça como o RicardoLuis esta dizendo …

import javax.swing.JFrame;


public class P extends JFrame{
	public P(){
	
		setSize(400,400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null); 
		setVisible(true);
	}
	
	public static void main(String [] args){
		P p = new P();		
	}
}
K

pow galera…

descobri o que era…

eu estava rodando o programa no eclipse como JavaBean e não com JavaApplication!!!

o méotod do RicardoLuis funcionou mas acho q todos os outros tb funcionam…

vivendo e aprendendo!!! hauieha

valew pela força galera!!!

Criado 6 de dezembro de 2007
Ultima resposta 6 de dez. de 2007
Respostas 21
Participantes 5