jScrollPane com vários jTextFields - [RESOLVIDO]

Galera, estou quebrando a cabeça para montar um formulário dinamico que vai montar vários campos num JPanel, podem ser adicionados novos campos dependendo de como está o banco de dados, ou seja eu monto o formulário de acordo com uma tabela no banco de dados, se eu inserir mais um campo em minha tabela no BD no meu formulário aparece esse campo automaticamente sem precisar criar o campo na munheca, isso está funcionando mas o problema é que estou prevendo que vou precisar de muitos campos mas o meu form quero deixar num tamanho fixo, aí pensei em jogar os campos num JPanel e adicionar uma barra de rolagem para poder visualizar todos os campos, já fiz de diversas formas mas não funciona, segue abaixo o código:

package Interface;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import ConsultasBD.getCamposGenerico;
import java.util.List;
import engines.VerificaPermissao;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.ArrayList;
import engines.GeraCampos;
import Objetos.Componente;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.BorderLayout;

/**
 * @author Gilson
 */
public class TelaGenerica extends JFrame implements ListSelectionListener  {

    public TelaGenerica(String user,String objeto,String clausula){
        super();
        this.usuario=user;
        this.objeto = objeto;
        initComponentes();
        if(new VerificaPermissao().getVisualizacao(objeto, usuario)==false){
            this.cancelaForm();
        }
    }

    private void initComponentes(){

        /*
         * Grupo de objetos responsáveis por
         * pegar os campos que aparecerão na tela
         */
        GeraCampos gC = new GeraCampos();
        gC.GeraCampos(objeto,usuario);
        List campos = gC.GetCampos();


        /*
         * Iniciando os componentes
         */

        scrollTabela = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        cmdSalvar = new JButton("Salvar");
        cmdExcluir = new JButton("Excluir");
        cmdNovo = new JButton("Novo");
        cmdCancelar = new JButton("Cancelar");

        /*
         * Definindo agumas propriedades do JFrame, como o título da janea e o evendo ao fechar a janela
         */
        setTitle(objeto);

        //this.setSize(600, 500);
        this.setContentPane(getJContentPane(campos,gC));
        this.setTitle("Testando.com.br");
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-400)/2, (screenSize.height-260)/2, 400, (campos.size()/2)*20 +150);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        this.setVisible(true);

    }

    private JPanel getpnlInputFields(List campos){
        if(pnlInputFields == null){

            GridLayout gridLayout = new GridLayout();
            gridLayout.setRows(campos.size()/2);
            gridLayout.setColumns(2);

            pnlInputFields = new JPanel();
            pnlFields = new JPanel();
            pnlInputFields.setLayout(gridLayout);
            pnlFields.setLayout(new java.awt.GridLayout(1, 1));


            int posX=10;
            int posY=10;
            int controle=0;

            for(int x=0;x<campos.size();x++){
                Componente cp = (Componente) campos.get(x);
                if(cp.getTipo().equals("JLabel") ){
                    JLabel jl = new JLabel(cp.getAlias(),SwingConstants.RIGHT);
                    jl.setName(cp.getNome());
                    pnlInputFields.add(jl,null);
                    controle=0;
                }else if(cp.getTipo().equals("JTextField")){
                    JTextField jt = new JTextField();
                    jt.setName(cp.getAlias());
                    cpStr = cpStr.trim() + cp.getNome().substring(0, cp.getNome().length());
                    if(x+1><campos.size()){cpStr = cpStr +",";}
                    if (cp.getPermissao()><= 3){ // pode editar=3, inserir=2 e excluir=1
                        jt.setEditable(true);
                    }else{
                        jt.setEditable(false);//permissão = 4
                    }
                    pnlInputFields.add(jt,null);
                    controle=1;
                }
                if (controle == 1){
                    posY=posY+25;
                }
            }

        }

        scrlPane.setViewportView(pnlInputFields);
        return pnlInputFields;
    }

    private JPanel getscrlPane(List campos){
        if(scrlPane == null){
            scrlPane = new JScrollPane();
            scrlPane.setViewportView(getpnlInputFields(campos));
            pnlCamp = new javax.swing.JPanel();
            pnlCamp.setLayout(new java.awt.GridLayout(1, 1));
            pnlCamp.add(scrlPane);

        }
        return pnlCamp;
    }

    private JPanel getpnlGrid(GeraCampos gC){
        pnlGrid = new javax.swing.JPanel();
        pnlGrid.setLayout(new java.awt.GridLayout(1, 1));
        


        scrollTabela = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();

        int z=0;
        String colunas = "";
        List col = new ArrayList();
        col = gC.getColunas();
        while(z<=col.size()-1){
            colunas = colunas + col.get(z);
            z++;
            if(z<=col.size()-1){colunas = colunas + ";";}
        }

        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] { },
                colunas.split(";")
        ){});


        tabela.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent ev){
                trataClickTabela(ev);
            }
        } );
        tabela.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent ke){
                trataKeyTabela(ke);
            }
        });

        scrollTabela.setViewportView(tabela);
        pnlGrid.add(scrollTabela);

        //Popula a tabela com os dados do BD
        getCamposGenerico gCG = new getCamposGenerico();
        regList = gCG.getCampos(objeto, cpStr);
        for(int x=0;x<regList.size();x++){
            javax.swing.table.DefaultTableModel dtm = (javax.swing.table.DefaultTableModel)tabela.getModel();
            dtm.addRow(regList.get(x).toString().split(";"));
        }

        return pnlGrid;
    }


    private JPanel getPnlButtons(){
        if (pnlButtons == null){
            pnlButtons = new JPanel();
            pnlButtons.setLayout(new FlowLayout());

            cmdNovo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    trataBotaoNovo();
                }
            });

            cmdCancelar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    cancelaForm();

                }
            });

            pnlButtons.add(cmdNovo,null);
            pnlButtons.add(cmdExcluir,null);
            pnlButtons.add(cmdSalvar,null);
            pnlButtons.add(cmdCancelar,null);

        }
        return pnlButtons;
    }


    private JPanel getJContentPane(List campos, GeraCampos gC){
        if(jContentPane == null){
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.setAutoscrolls(true);
            jContentPane.add(getscrlPane(campos),BorderLayout.NORTH);
            //jContentPane.add(getpnlInputFields(campos),BorderLayout.NORTH);

            jContentPane.add(getpnlGrid(gC),BorderLayout.CENTER);
            jContentPane.add(getPnlButtons(),BorderLayout.SOUTH);
        }
        return jContentPane;
    }


    /*
     * Método chamado no fechamento da tela
     */
    private void exitForm() {
        //this.setDefaultCloseOperation(HIDE_ON_CLOSE);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        System.exit(0);
    }

    private void cancelaForm(){
        this.setVisible(false);
        exitForm();
    }


    /*
     * método chamado quando alguma tecla é precionada dentro da tabela
     */
    private void trataKeyTabela(KeyEvent k){
        if (k.getKeyCode() == 40 ){

            String colNome="";
            for(int z=0;z< tabela.getColumnCount();z++){

                colNome = tabela.getColumnName(z);
                Component Comp[] = this.pnlInputFields.getComponents();
                for(int x=0; x >< Comp.length;x++){
                    //JTextField jt=new JTextField("verifica");
                    if(Comp[x] instanceof  JTextField){
                        if(Comp[x].getName().equalsIgnoreCase(colNome)){
                            ((JTextField) Comp[x]).setText(((JTable) k.getSource()).getValueAt(tabela.getSelectedRow()+1, z).toString().trim());
                        }
                        //javax.swing.JOptionPane.showMessageDialog(null,((JTextField)Comp[x]).getName()+ " - "+Comp.length+" - "+x);
                    }
                }
            }
        }else if( k.getKeyCode() == 38 ){
            
            String colNome="";
            for(int z=0;z< tabela.getColumnCount();z++){
            
                colNome = tabela.getColumnName(z);
                Component Comp[] = this.pnlInputFields.getComponents();
                for(int x=0; x < Comp.length;x++){
                    //JTextField jt=new JTextField("verifica");
                    if(Comp[x] instanceof  JTextField){
                        if(Comp[x].getName().equalsIgnoreCase(colNome)){
                            ((JTextField) Comp[x]).setText(((JTable) k.getSource()).getValueAt(tabela.getSelectedRow()-1, z).toString().trim());
                        }
                        //javax.swing.JOptionPane.showMessageDialog(null,((JTextField)Comp[x]).getName()+ " - "+Comp.length+" - "+x);
                    }
                }
            }
        }
    }

    /*
     * método chamado quando ocorre algum click do mouse dentro da tabela
     */
    private void trataClickTabela(MouseEvent e){
        if (e.getButton()==1){
            
            String colNome="";
            for(int z=0;z< tabela.getColumnCount();z++){
            
                colNome = tabela.getColumnName(z);
                Component Comp[] = this.pnlInputFields.getComponents();
                for(int x=0; x < Comp.length;x++){
                    //JTextField jt=new JTextField("verifica");
                    if(Comp[x] instanceof  JTextField){
                        if(Comp[x].getName().equalsIgnoreCase(colNome)){
                            ((JTextField) Comp[x]).setText(((JTable) e.getSource()).getValueAt(tabela.getSelectedRow(), z).toString().trim());
                        }
                        //javax.swing.JOptionPane.showMessageDialog(null,((JTextField)Comp[x]).getName()+ " - "+Comp.length+" - "+x);
                    }
                }
            }

            //txtCodigo.setText(((JTable) e.getSource()).getValueAt(tabela.getSelectedRow(), 0).toString().trim());
            //txtNome.setText(((JTable) e.getSource()).getValueAt(tabela.getSelectedRow(), 1).toString().trim());
        }else  if (e.getClickCount() == 2){
            System.out.println(" double click direito" );
        }
    }

    /*
     * Método que é chamado ao clicar no botão novo
     */
    private void trataBotaoNovo(){
        //txtCodigo.setText((String.valueOf(getEsp.getLastEspecialidades()+1)));
        //txtNome.setText(null);
        //txtNome.requestFocus();
        NovoRegistro=true;
    }



    /*
     * Método Main
     */
    public static void main(String[] Args){
        /*
         * Aqui mandamos iciciar um novo objeto EspecialidadesForm
         */
        new TelaGenerica("Gilson","especialidades","esp_Nome='Ginecologia'");
    }


    /*
     * Definições de variáveis
     */
    JTable tabela;
    JScrollPane scrollTabela;
    JPanel pnTabela;
    JPanel pnTela;
    List regList;
    
    JButton cmdSalvar;
    JButton cmdExcluir;
    JButton cmdNovo;
    JButton cmdCancelar;
    boolean NovoRegistro=false;
    String usuario;
    String objeto;
    String cpStr = " ";
    private javax.swing.JScrollPane scrlPane;

    private javax.swing.JPanel jContentPane;
    private javax.swing.JPanel pnlButtons;
    private javax.swing.JPanel pnlInputFields;
    private javax.swing.JPanel pnlFields;
    private javax.swing.JPanel pnlGrid;
    javax.swing.JPanel pnlCamp;


    public void valueChanged(ListSelectionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }


}

Segue a imagem do form:

Agradeço ajuda !

Não faço a mínima idéia de qual é o seu erro. De qualquer maneira, segue abaixo um exemplo bobo de um JScrollPane com JTextFields e JComboBoxes.

package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ExemploJScrollPane extends JFrame {
	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JScrollPane scpMain = null;
	private JPanel pnlButtons = null;
	private JButton btnOK = null;
	private JButton btnCancel = null;
	private JPanel pnlInputFields = null;
	private JLabel lblName = null;
	private JTextField txtName = null;
	private JLabel lblAddress = null;
	private JTextField txtAddress = null;
	private JLabel lblPhone = null;
	private JTextField txtPhone = null;
	private JLabel lblCountry = null;
	private JComboBox cboCountry = null;
	private JLabel lblState = null;
	private JComboBox cboState = null;

	private JScrollPane getScpMain() {
		if (scpMain == null) {
			scpMain = new JScrollPane();
			scpMain.setViewportView(getPnlInputFields());
		}
		return scpMain;
	}
	private JPanel getPnlButtons() {
		if (pnlButtons == null) {
			pnlButtons = new JPanel();
			pnlButtons.setLayout(new FlowLayout());
			pnlButtons.add(getBtnOK(), null);
			pnlButtons.add(getBtnCancel(), null);
		}
		return pnlButtons;
	}
	private JButton getBtnOK() {
		if (btnOK == null) {
			btnOK = new JButton();
			btnOK.setText("OK");
		}
		return btnOK;
	}
	private JButton getBtnCancel() {
		if (btnCancel == null) {
			btnCancel = new JButton();
			btnCancel.setText("Cancel");
		}
		return btnCancel;
	}
	private JPanel getPnlInputFields() {
		if (pnlInputFields == null) {
			lblState = new JLabel();
			lblState.setText("State");
			lblCountry = new JLabel();
			lblCountry.setText("Country");
			lblPhone = new JLabel();
			lblPhone.setText("Phone");
			lblAddress = new JLabel();
			lblAddress.setText("Address");
			lblName = new JLabel();
			lblName.setText("Name");
			GridLayout gridLayout = new GridLayout();
			gridLayout.setRows(5);
			gridLayout.setColumns(2);
			pnlInputFields = new JPanel();
			pnlInputFields.setLayout(gridLayout);
			pnlInputFields.add(lblName, null);
			pnlInputFields.add(getTxtName(), null);
			pnlInputFields.add(lblAddress, null);
			pnlInputFields.add(getTxtAddress(), null);
			pnlInputFields.add(lblPhone, null);
			pnlInputFields.add(getTxtPhone(), null);
			pnlInputFields.add(lblCountry, null);
			pnlInputFields.add(getCboCountry(), null);
			pnlInputFields.add(lblState, null);
			pnlInputFields.add(getCboState(), null);
		}
		return pnlInputFields;
	}
	private JTextField getTxtName() {
		if (txtName == null) {
			txtName = new JTextField();
		}
		return txtName;
	}
	private JTextField getTxtAddress() {
		if (txtAddress == null) {
			txtAddress = new JTextField();
		}
		return txtAddress;
	}
	private JTextField getTxtPhone() {
		if (txtPhone == null) {
			txtPhone = new JTextField();
		}
		return txtPhone;
	}
	private JComboBox getCboCountry() {
		if (cboCountry == null) {
			cboCountry = new JComboBox();
		}
		return cboCountry;
	}
	private JComboBox getCboState() {
		if (cboState == null) {
			cboState = new JComboBox();
		}
		return cboState;
	}
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				ExemploJScrollPane thisClass = new ExemploJScrollPane();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}
	public ExemploJScrollPane() {
		super();
		initialize();
	}
	private void initialize() {
		this.setSize(300, 150);
		this.setContentPane(getJContentPane());
		this.setTitle("Teste JScrollPane");
	}
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getScpMain(), BorderLayout.CENTER);
			jContentPane.add(getPnlButtons(), BorderLayout.SOUTH);
		}
		return jContentPane;
	}
}


Então amigo, o erro é o seguinte:
Pegue esse seu código e coloque entre o panel dos campos e o panel dos botões mais um panel e nesse coloque uma JTable e faça com que o panel dos campos funcione com barra de rolagem.
Esse é o problema, com os dois panels como você fez, o scroll funciona na boa mas quando coloco um terceiro panel com uma JTable entre os dois que já existem, aí o scroll dos campos para de funcionar.

Espero ter conseguido explicar.

Abraços

Acho que os JScrollPanes estão com problemas no seu dimensionamento. Uma forma de você contornar isso é pôr tanto o seu JScrollPane dos JTextFields quanto o seu JScrollPane do JTable em um JSplitPane. Então você deixa o JSplitPane com a proporção adequada que você quer. Exemplo:

package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class ExemploJScrollPane extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JScrollPane scpMain = null;
    private JPanel pnlButtons = null;
    private JButton btnOK = null;
    private JButton btnCancel = null;
    private JPanel pnlInputFields = null;
    private JLabel lblName = null;
    private JTextField txtName = null;
    private JLabel lblAddress = null;
    private JTextField txtAddress = null;
    private JLabel lblPhone = null;
    private JTextField txtPhone = null;
    private JLabel lblCountry = null;
    private JComboBox cboCountry = null;
    private JLabel lblState = null;
    private JComboBox cboState = null;
    private JSplitPane splMain = null;
    private JScrollPane scpTable = null;
    private JTable tblTable = null;

    private JScrollPane getScpMain() {
        if (scpMain == null) {
            scpMain = new JScrollPane();
            scpMain.setViewportView(getPnlInputFields());
        }
        return scpMain;
    }
    private JPanel getPnlButtons() {
        if (pnlButtons == null) {
            pnlButtons = new JPanel();
            pnlButtons.setLayout(new FlowLayout());
            pnlButtons.add(getBtnOK(), null);
            pnlButtons.add(getBtnCancel(), null);
        }
        return pnlButtons;
    }
    private JButton getBtnOK() {
        if (btnOK == null) {
            btnOK = new JButton();
            btnOK.setText("OK");
        }
        return btnOK;
    }
    private JButton getBtnCancel() {
        if (btnCancel == null) {
            btnCancel = new JButton();
            btnCancel.setText("Cancel");
        }
        return btnCancel;
    }
    private JPanel getPnlInputFields() {
        if (pnlInputFields == null) {
            lblState = new JLabel();
            lblState.setText("State");
            lblCountry = new JLabel();
            lblCountry.setText("Country");
            lblPhone = new JLabel();
            lblPhone.setText("Phone");
            lblAddress = new JLabel();
            lblAddress.setText("Address");
            lblName = new JLabel();
            lblName.setText("Name");
            GridLayout gridLayout = new GridLayout();
            gridLayout.setRows(5);
            gridLayout.setColumns(2);
            pnlInputFields = new JPanel();
            pnlInputFields.setLayout(gridLayout);
            pnlInputFields.add(lblName, null);
            pnlInputFields.add(getTxtName(), null);
            pnlInputFields.add(lblAddress, null);
            pnlInputFields.add(getTxtAddress(), null);
            pnlInputFields.add(lblPhone, null);
            pnlInputFields.add(getTxtPhone(), null);
            pnlInputFields.add(lblCountry, null);
            pnlInputFields.add(getCboCountry(), null);
            pnlInputFields.add(lblState, null);
            pnlInputFields.add(getCboState(), null);
        }
        return pnlInputFields;
    }
    private JTextField getTxtName() {
        if (txtName == null) {
            txtName = new JTextField();
        }
        return txtName;
    }
    private JTextField getTxtAddress() {
        if (txtAddress == null) {
            txtAddress = new JTextField();
        }
        return txtAddress;
    }
    private JTextField getTxtPhone() {
        if (txtPhone == null) {
            txtPhone = new JTextField();
        }
        return txtPhone;
    }

    private JComboBox getCboCountry() {
        if (cboCountry == null) {
            cboCountry = new JComboBox();
        }
        return cboCountry;
    }
    private JComboBox getCboState() {
        if (cboState == null) {
            cboState = new JComboBox();
        }
        return cboState;
    }
    private JSplitPane getSplMain() {
        if (splMain == null) {
            splMain = new JSplitPane();
            splMain.setOrientation(JSplitPane.VERTICAL_SPLIT);
            splMain.setResizeWeight(0.5D);
            splMain.setBottomComponent(getScpTable());
            splMain.setTopComponent(getScpMain());
        }
        return splMain;
    }
    private JScrollPane getScpTable() {
        if (scpTable == null) {
            scpTable = new JScrollPane();
            scpTable.setViewportView(getTblTable());
        }
        return scpTable;
    }
    private JTable getTblTable() {
        if (tblTable == null) {
            tblTable = new JTable();
            // Só para não deixar em branco - obviamente você não deve
            // usar DefaultTableModel em uma aplicação normal. 
            tblTable.setModel(new DefaultTableModel (new String[][]{
                {"Joseph", "8 Mulholland Drive", "555-5555", "123-4567-8"},
                {"Apple", "One Infinite Loop", "777-7777", "823-4568-7"},
                {"Sun", "4150 Network Circle", "555-9SUN", "123-7777-8"},
                {"Oracle", "500 Oracle Parkway", "1-800-ORACLE1", "444-7777-8"},
                {"Microsoft", "One Microsoft Way", "882-8080", "444-9999-8"},
                {"Red Hat", "1801 Varsity Drive", "754-3700", "333-3339-9"},
                }, 
                new String[]{"Name", "Address", "Phone", "SSN"}));
        }
        return tblTable;
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ExemploJScrollPane thisClass = new ExemploJScrollPane();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }
    public ExemploJScrollPane() {
        super();
        initialize();
    }
    private void initialize() {
        this.setSize(300, 293);
        this.setContentPane(getJContentPane());
        this.setTitle("Teste JScrollPane");
    }
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getSplMain(), BorderLayout.CENTER);
            jContentPane.add(getPnlButtons(), BorderLayout.SOUTH);
        }
        return jContentPane;
    }
} // @jve:decl-index=0:visual-constraint="10,10"


Valew !

Era exatamente isso que eu precisava, muito obrigado !

:smiley: