Fixar tamanho JTabbedPane

5 respostas
andretco

Oi Pessoal, tenho uma dúvida :

  • Como posso fixar o tamanho de um JTabbedPane de modo que ao redimensionar o JFrame, o JTabbedPane não se adapte ao tamanho da janela??? Estou usando o GridBagLayout nos JPanels.

Eu gostaria que funcionasse como a janela de Preferências do Eclipse-Europa (Window -> Preferences…).

Valeu!.

5 Respostas

ViniGodoy

PS: Uma maneira fácil de fazer isso é a seguinte:
Ponha um painel ao lado do TabbedPane e deixe-o capaz de crescer em x.
Ponha outro painel abaixo do TabbedPane e deixe-o capaz de crescer em y.

Os paineis “empurram” o TabbedPane e, não só ele fica do tamanho certo, como também o mantém no canto que você quiser.

andretco

tentei, mas não consegui deixar que os painéis creceram só em X ou só em Y. Como se faz isso? não é usando alguns dos métodos abaixo né?: :?:

panel1.applyComponentOrientation(o);
panel1.setAlignmentX(alignmentX);
panel1.setAlignmentY(alignmentY);
panel1.setComponentOrientation(o);

observei que se coloco o JTabbedPane no norte do JFrame (seteado com BorderLayout) e um painel no centro e o outro painel na direita, o JTabbedPane não se modifica em Y (beleza!) mas se modifica em X, ou seja se adapta ao tamanho da janela :x

Também tentei rodear o JTabbedPane com painéis mas também não deu certo. :lol:

Poderias explicar-me um pouco mais porfavor?

Muito Obrigado.

ViniGodoy

O segredo está em manter o weigthx e o weigthy do seu TabbedPane em 0. É através dessa propriedade que o Gridbag sabe se um componente vai crescer e o quanto.

Se dois componentes tem weigthtx 2 e 1, por exemplo, significa que um deve se esticar e, no final, um deve ter o dobro do tamanho do outro. Um weigthx de 0 indica que o componente não deve se esticar e deve manter o seu preferredSize.

Então, faça o seguinte.
1. Defina um preferredSize para o seu JTabbedPane;
2. Deixe o seu TabbedPane com weigthx e weigthy em valor 0;
3. Adicione dois paneis: um na lateral e outro embaixo do pane, e faça os wegths deles serem 1.

Exemplo abaixo:

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class TabbedSample extends JDialog
{

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JTabbedPane tabSample = null;
    private JPanel pnlLeft = null;
    private JPanel pnlBottom = null;
    private JPanel tblTabbed = null;

    public TabbedSample(Frame owner)
    {
        super(owner);
        initialize();
    }

    private void initialize()
    {
        this.setSize(387, 275);
        this.setTitle("TabbedPane Sample");
        this.setContentPane(getJContentPane());
    }

    private JPanel getJContentPane()
    {
        if (jContentPane == null)
        {
            GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
            gridBagConstraints2.gridx = 0;
            gridBagConstraints2.weightx = 0.0;
            gridBagConstraints2.weighty = 1.0;
            gridBagConstraints2.gridy = 1;
            GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
            gridBagConstraints1.gridx = 1;
            gridBagConstraints1.weightx = 1.0;
            gridBagConstraints1.weighty = 0.0;
            gridBagConstraints1.gridy = 0;
            GridBagConstraints gridBagConstraints = new GridBagConstraints();
            gridBagConstraints.fill = GridBagConstraints.NONE;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.weightx = 0.0;
            gridBagConstraints.weighty = 0.0;
            gridBagConstraints.anchor = GridBagConstraints.WEST;
            gridBagConstraints.gridx = 0;
            jContentPane = new JPanel();
            jContentPane.setLayout(new GridBagLayout());
            jContentPane.add(getTabSample(), gridBagConstraints);
            jContentPane.add(getPnlLeft(), gridBagConstraints1);
            jContentPane.add(getPnlBottom(), gridBagConstraints2);
        }
        return jContentPane;
    }

    /**
     * Cria o tabbed pane. É importante setar o preferred size dele
     * para o tamanho que você deseja. Certifique-se também que as
     * GridBadConstraints dele não definem weight para o pane.
     */
    private JTabbedPane getTabSample()
    {
        if (tabSample == null)
        {
            tabSample = new JTabbedPane();
            tabSample.setPreferredSize(new Dimension(300, 200));
            tabSample.addTab(null, null, getTblTabbed(), null);
        }
        return tabSample;
    }

    /**
     * O painel que estica na esquerda deve ter o o weigthx definido 
     * para 1. Isso fará a largura dele esticar a tela inteira.
     * Assim ele empurra o Pane para a direita.
     */
    private JPanel getPnlLeft()
    {
        if (pnlLeft == null)
        {
            pnlLeft = new JPanel();
            pnlLeft.setLayout(new GridBagLayout());
        }
        return pnlLeft;
    }

    /**
     * O painel que estica na parte de baixo deve ter o o weigthy 
     * definido para 1. Isso fará a altura dele esticar a tela inteira.
     * Assim ele empurra o Pane para cima.
     */
    private JPanel getPnlBottom()
    {
        if (pnlBottom == null)
        {
            pnlBottom = new JPanel();
            pnlBottom.setLayout(new GridBagLayout());
        }
        return pnlBottom;
    }

    /**
     * Um painel, só para dar para ver a aba no tabbed.
     * @return
     */
    private JPanel getTblTabbed()
    {
        if (tblTabbed == null)
        {
            tblTabbed = new JPanel();
            tblTabbed.setLayout(new GridBagLayout());
        }
        return tblTabbed;
    }

}
andretco

Muito bom e didático o exemplo.

Neste momento estou aplicando a sua metodologia no meu código.

Novamente muito obrigado.

Valeu mesmo.

andretco

depois de olhar a documentação, alguns posts, etc... consegui fazer o que eu queria..... :)

o código do seu exemplo me ajudou....mas ao deixar a janela menor que tabbed pane, este ficava bem pequeno (se comprimia um montão).

então a solução era deixar o tabbedPane em um painel sem layout.

aqui vai o código de exemplo.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class MyFrame extends JFrame{
	
	
	private static final long serialVersionUID = 1L;
	private JPanel panel1=null;
	private JPanel panel2=null;
	private JPanel tab1Panel=null;
	private JPanel tab2Panel=null;
	private JTabbedPane tabbedPane=null;
	private JButton okBtn=null;
	private JButton cancelBtn=null;
	private JTable table=null;  
	private JScrollPane scrollPane=null;
	private DefaultTableModel tableModel=null;
	
	
	private final String [] columnNames = {"Add Buttons", "Name", "Geometry", "Painted"};
	
	private Object datas[][]={
			{new Boolean(true),"Joao","Rectangle",new Boolean(true)},
			{new Boolean(true),"Maria","Hexagon",new Boolean(true)},
			{new Boolean(true),"André","Circle",new Boolean(true)},
			{new Boolean(true),"Ze","Oval",new Boolean(true)}
			
	};
	
	
	public MyFrame(){
		
		this.getContentPane().setLayout(new BorderLayout());
		this.panel1 = new JPanel();
		this.panel2 = new JPanel();
		this.tab1Panel = new JPanel();
		this.tab2Panel = new JPanel();
		this.tabbedPane = new JTabbedPane();
		this.okBtn = new JButton("OK");
		this.cancelBtn = new JButton("Cancel");

		this.panel1.setLayout(null);
		this.panel2.setLayout(new FlowLayout());

		this.tableModel = new DefaultTableModel(this.datas,this.columnNames);
		this.table = new JTable(this.tableModel);  
		this.scrollPane = new JScrollPane(this.table);
		
		this.tab1Panel.add(this.scrollPane);
		
		
		this.tabbedPane.addTab("Tab1", this.tab1Panel);
		this.tabbedPane.addTab("Tab2", this.tab2Panel);
				
		this.tabbedPane.setBounds(0, 0, 470, 200);
		this.panel1.add(this.tabbedPane);
		this.panel2.add(this.okBtn);
		this.panel2.add(this.cancelBtn);
		
		this.add(this.panel1,BorderLayout.CENTER);
		this.add(this.panel2,BorderLayout.SOUTH);
				
	}
		

	public static void main(String[] args) {
		
		MyFrame frame = new MyFrame();
		frame.setPreferredSize(new Dimension(600,300));
		frame.pack();
		frame.setVisible(true);
		
	}

}
não sei se é bom fazer isto.... :?
Criado 16 de dezembro de 2007
Ultima resposta 19 de dez. de 2007
Respostas 5
Participantes 2