Por JPanel no centro de JFrame

2 respostas
T

Ola,

Eu quero que o JPanel 'p' esteja no centro de JFrame. Eu tentei com getContentPane().add(p, BorderLayout.CENTER);mas não funcionava.

Obrigado pela sua ajuda

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;




public class Radio extends JFrame{
	JRadioButton blue = new JRadioButton("Blue");
	JRadioButton red = new JRadioButton("Red");
	
	JRadioButton green = new JRadioButton("Green");

	public Radio(){
		JPanel p = new JPanel();
		p.setBackground(Color.RED);
		p.setSize(100, 100);
		getContentPane().add(p, BorderLayout.CENTER);;
		add(blue);
		add(red);
		add(green);
		setLayout(new FlowLayout());
		setVisible(true);
		pack();
		setSize(new Dimension(300, 300));
		addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
	
	public static void main(String[] args){
		new Radio();
	}
}

2 Respostas

S

tmtwd,

Você está utilizando o Layout FlowLayout no seu JFrame o que implica que os componente s serão mostrados da esquerda para direita no seu frame de acordo com a ordem que você incluiu.

Fiz algumas modificações no seu construtor, não sei bem se é isso que você estava querendo fazer:

public Radio(){  
        JPanel p = new JPanel();  
        p.setBackground(Color.RED);  
        p.setSize(100, 100);  
        setLayout(new BorderLayout());  
        getContentPane().add(p, BorderLayout.CENTER);
        JPanel painelBotoes = new JPanel();
        getContentPane().add(painelBotoes, BorderLayout.NORTH);
        painelBotoes.add(blue);  
        painelBotoes.add(red);  
        painelBotoes.add(green);  
        
        setVisible(true);  
        pack();  
        setSize(new Dimension(300, 300));  
        addWindowListener(new WindowAdapter() {  
  
            public void windowClosing(WindowEvent e) {  
                System.exit(0);  
            }  
        });  
    }
T

Obrigado! Funciona muito bem

Criado 19 de outubro de 2014
Ultima resposta 24 de out. de 2014
Respostas 2
Participantes 2