Herança visual com swing

4 respostas
java
C

bom dia pessoal
preciso fazer uma herança visual no java usando swing, o que seria isso
tenho que ter um cabeçalho base e alguns botoes no rodapé (que todos os formulários CRUD devem ter), então o que eu fiz foi criar esse formulário base e herdei no formulário que queria essa herança visual e não funcionou.

alguém pode me ajudar nessa parte?

obrigado
abs

4 Respostas

T

“Não funcionou” é muito vago. O que não funcionou exatamente? Está usando Swing? Você criou um JFrame personalizado, mas os componentes a mais (labels, botões) não aparecem? Como você está chamando esses JFrames no main?

Seja mais específico.

Abraço.

C

mals pela falta de informação, vamos la

estou usando o javax.swing.JFrame para criar os formularios.

o que eu fiz :
criei um BaseForm e nele, criei 3 panels (cabeçalho, corpo e rodapé).
fiz a herança dele no formulário ExemploForm, e o que eu esperava com isso, que a formatação visual que criei no BaseForm fosse replicada (aparecer os panel, botao e tudo mais) para o ExemploForm.

acho que é isso, veja se consegui explicar melhor por favor
abs

segue o codigo do BaseForm

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.marvin.ui;

/**
 *
 * @author Mercurio
 */
public class BaseForm extends javax.swing.JFrame {

    /**
     * Creates new form BaseForm
     */
    public BaseForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panelCabecalho = new javax.swing.JPanel();
        panelCorpo = new javax.swing.JPanel();
        panelBotao = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panelCabecalho.setBackground(new java.awt.Color(255, 255, 204));

        javax.swing.GroupLayout panelCabecalhoLayout = new javax.swing.GroupLayout(panelCabecalho);
        panelCabecalho.setLayout(panelCabecalhoLayout);
        panelCabecalhoLayout.setHorizontalGroup(
            panelCabecalhoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 609, Short.MAX_VALUE)
        );
        panelCabecalhoLayout.setVerticalGroup(
            panelCabecalhoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        panelCorpo.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout panelCorpoLayout = new javax.swing.GroupLayout(panelCorpo);
        panelCorpo.setLayout(panelCorpoLayout);
        panelCorpoLayout.setHorizontalGroup(
            panelCorpoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelCorpoLayout.setVerticalGroup(
            panelCorpoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 275, Short.MAX_VALUE)
        );

        panelBotao.setBackground(new java.awt.Color(255, 255, 204));

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 51, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelCabecalho, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panelCorpo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(panelCabecalho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelCorpo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BaseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BaseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BaseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BaseForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BaseForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel panelBotao;
    private javax.swing.JPanel panelCabecalho;
    private javax.swing.JPanel panelCorpo;
    // End of variables declaration                   
}

e no formulario de ExemploForm

package com.marvin.ui;

    public class ExemploForm extends BaseForm {

    /**
     * Creates new form ExemploForm
     */
    public ExemploForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 533, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 324, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ExemploForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ExemploForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ExemploForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ExemploForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ExemploForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}
T

No construtor do seu form derivado, você precisa chamar o construtor do form base, que é onde os componentes são criados. Algo como:

public ExemploForm() {
  super(); // chama o construtor de BaseForm
  initComponents(); // cria os componentes específicos desse form
}

Herança de componentes visuais sempre é um pouco complicada, e o NetBeans não ajuda muito, pois gera muito código. Aqui um exemplo simplificado de como isso funciona:

Form Base:

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;

public class FormBase extends JFrame {
	
	protected JLabel textoQualquer;

	public FormBase(){
		super("FormBase");

		System.out.println("Form Base Criado");
		
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		
		setLayout(new BorderLayout());
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		textoQualquer = new JLabel("TEXTO QUALQUER ALINHADO NO TOPO, SÓ PRA EXEMPLIFICAR");
		
		getContentPane().add(textoQualquer, BorderLayout.NORTH);
		
		pack();
	}
}

Form Derivado:

import javax.swing.*;

public class FormExtendido extends FormBase {

	public FormExtendido(){
		super();
		setTitle("Form Extendido");
		
		System.out.println("Form Extendido Criado");
	}
}

Classe com o main:

import javax.swing.*;

public class ExForms {
	public static void main(String args[]){

		java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormExtendido().setVisible(true);
            }
        });
	}
}

Abraço.

C

valeu…funcionou…com isso ja me viro com todo o resto

obrigado
abs

Criado 21 de outubro de 2017
Ultima resposta 21 de out. de 2017
Respostas 4
Participantes 2