JScrollPane não aparece - [RESOLVIDO]

E ai pessoal do GUJ, acho que o título ja diz tudo, mas venho aqui pedir a ajuda de vocês pois a minha JScrollPane não aparece na tela.
Aqui esta o código que estou usando:

JScrollPane scroll;

scroll = new JScrollPane(taDescricao, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scroll.setPreferredSize(new Dimension (450, 110));
		scroll.setVisible(true);
		scroll.setBounds(390, 30, 20, 250);

this.add(scroll);

Muito obrigado pela atenção e até logo.

Att.: Raytek.

Ué, e não tem nada dentro do ScrollPane?

Se não tiver, não vai aparecer mesmo (você pediu barra vertical só se necessária e nunca mostrar a horizontal. Sem nada a barra vertical não será necessária).

Tópico movido para interface gráfica.

Será que alguem tem como postar algum exemplo, de como colocar a barra?

Up… :smiley:

JScrollPane scroll = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scroll.setPreferredSize(new Dimension (450, 110)); scroll.setVisible(true); scroll.setBounds(390, 30, 20, 250); JOptionPane.showMessageDialog(scroll, scroll);

Obrigado pela resposta só que estou tentando adicionar JScrollPane em uma JTextArea alguem sabe como colocar?

não seria o contrário?

Não sei ao certo pois nunca usei tais componentes antes, se puder ajudar agradeço…

mas explique melhor teu objetivo então, ficar encaixando um componente no outro sem razão é meio confuso pra quem vai te ajudar…

Meu objetivo é criar uma JTextArea que recebe a descrição de um produto e nela eu queria uma barra de rolagem vertical caso o texto ultrapasse seu tamanho. Ficou mais claro?

Vê se te ajuda :arrow: http://www.guj.com.br/java/99285-scrollpane-em-jtextarearesolvido pelo menos o tópico está em [RESOLVIDO] :wink:

:thumbup:

No meu caso não resolveu, vou postar o código fonte completo para maires detalhes:

[code]package br.edu.etec.hortolandia.papercad.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.ScrollPane;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

import br.edu.etec.hortolandia.papercad.dao.MidiaDAO;
import br.edu.etec.hortolandia.papercad.model.Midia;

public class Tela extends JFrame implements ActionListener{

/**
 * 
 */
private static final long serialVersionUID = 1L;
JLabel lId, lNome, lDescricao, lAtivo, lSim, lNao, lTipo, lAdm, lMod, lDef, imagem2, lOutro;
JTextField txId, txNome;
JTextArea taDescricao;
JButton btInserir, btAlterar, btExcluir, btLocalizar, btLimpar, btListar, btConfirmar, btSair;
JRadioButton jrbAtivo1, jrbAtivo2, jrbAdm, jrbMod, jrbDef, jrbOutro;
ButtonGroup bgGrupo1, bgGrupo2;
ImageIcon imagem;
JScrollPane scroll;

Midia mid = new Midia();
MidiaDAO conex = new MidiaDAO();

public Tela(){
	
	this.setTitle("Papercad - Cadastro de Mídias de Comunicação v0.01");
	this.setSize(700,400);
	this.setLayout(null);
	this.setUndecorated(false);
	this.setLocationRelativeTo(null);
	getContentPane().setBackground(new Color(230,230,250));
	
    Toolkit kit = Toolkit.getDefaultToolkit();  
	Image img = kit.getImage("pen.png");
	this.setIconImage(img);

	imagem = new ImageIcon("text.png");
	imagem2 = new JLabel(imagem);
	imagem2.setBounds(400, 10, 200, 200);
	
	//Coluna, Linha , Largura e Altura
	JLabel lId = new JLabel("Id: ");
	lId.setBounds(10,10,80,20);
	JLabel lNome = new JLabel("Nome: ");
	lNome.setBounds(10,40,80,20);
	JLabel lDescricao = new JLabel("Descricao:");
	lDescricao.setBounds(390,10,80,20);
	JLabel lAtivo = new JLabel("Registro Ativo");
	lAtivo.setBounds(10, 160, 80, 20);
	JLabel lSim = new JLabel("Sim");
	lSim.setBounds(40, 190, 80, 20);
	JLabel lNao = new JLabel("Não");
	lNao.setBounds(40, 210, 80, 20);
	JLabel lTipo = new JLabel("Tipo de Midia");
	lTipo.setBounds(190, 160, 100, 20);
	JLabel lAdm = new JLabel("Audiovisual");
	lAdm.setBounds(220, 190, 100, 20);
	JLabel lMod = new JLabel("Visual");
	lMod.setBounds(220, 210, 80, 20);
	JLabel lDef = new JLabel("Audio");
	lDef.setBounds(220, 230, 80, 20);
	JLabel lOutro = new JLabel("Outro");
	lOutro.setBounds(220, 250, 80, 20);
	
	txId = new JTextField();
	txId.setBounds(80,10,270,20);
	txNome = new JTextField();
	txNome.setBounds(80,40,270,20);
	
	scroll = new JScrollPane(taDescricao,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);    
	scroll.setPreferredSize(new Dimension (450, 110));    
	scroll.setVisible(true);    
	scroll.setBounds(390, 30, 20, 250);
	
	taDescricao = new JTextArea();
	taDescricao.setLineWrap(true);
	taDescricao.setWrapStyleWord(true);
	taDescricao.setBounds(390,30,270,250);
	
	jrbAtivo1 = new JRadioButton ();
	jrbAtivo1.setBounds(20, 190, 20, 20);
	jrbAtivo1.setSelected (true);
	jrbAtivo1.addActionListener(this);
	jrbAtivo2 = new JRadioButton ();
	jrbAtivo2.setBounds(20, 210, 20, 20);
	jrbAtivo2.setSelected (false);
	jrbAtivo2.addActionListener(this);
	jrbAdm = new JRadioButton ();
	jrbAdm.setBounds(200, 190, 20, 20);
	jrbAdm.setSelected (false);
	jrbAdm.addActionListener(this);
	jrbMod = new JRadioButton ();
	jrbMod.setBounds(200, 210, 20, 20);
	jrbMod.setSelected (false);
	jrbMod.addActionListener(this);
	jrbDef = new JRadioButton ();
	jrbDef.setBounds(200, 230, 20, 20);
	jrbDef.setSelected (true);
	jrbDef.addActionListener(this);
	jrbOutro = new JRadioButton();
	jrbOutro.setBounds(200, 250, 20, 20);
	jrbOutro.setSelected(false);
	jrbOutro.addActionListener(this);
	
	bgGrupo1 = new ButtonGroup();
    bgGrupo1.add(jrbAtivo1);
    bgGrupo1.add(jrbAtivo2);
    bgGrupo2 = new ButtonGroup();
    bgGrupo2.add(jrbAdm);
    bgGrupo2.add(jrbMod);
    bgGrupo2.add(jrbDef);
    bgGrupo2.add(jrbOutro);
	
	btInserir = new JButton("Inserir");
	btInserir.setBounds(10,290,100,20);
	btInserir.addActionListener(this);
	btAlterar = new JButton("Alterar");
	btAlterar.setBounds(120,290,100,20);
	btAlterar.addActionListener(this);
	btAlterar.setEnabled(false);
	btExcluir = new JButton("Excluir");
	btExcluir.setBounds(230,290,100,20);
	btExcluir.addActionListener(this);
	btExcluir.setEnabled(false);
	btLocalizar = new JButton("Localizar");
	btLocalizar.setBounds(340,290,100,20);
	btLocalizar.addActionListener(this);
	btLimpar = new JButton("Limpar");
	btLimpar.setBounds(450,290,100,20);
	btLimpar.addActionListener(this);
	btListar = new JButton("Listar");
	btListar.setBounds(560,290,100,20);
	btListar.addActionListener(this);
	btConfirmar = new JButton("Confirmar");
	btConfirmar.setBounds(230,320,100,20);
	btConfirmar.addActionListener(this);
	btSair = new JButton("Sair");
	btSair.setBounds(340,320,100,20);
	btSair.addActionListener(this);
	
	this.add(lId);
	this.add(lNome);
	this.add(lDescricao);
	this.add(txId);
	this.add(txNome);
	this.add(taDescricao);
	this.add(btInserir);
	this.add(btAlterar);
	this.add(btExcluir);
	this.add(btLocalizar);
	this.add(btLimpar);
	this.add(btListar);
	this.add(btConfirmar);
	this.add(btSair);
	this.add(jrbAtivo1);
	this.add(jrbAtivo2);
	this.add(lAtivo);
	this.add(lSim);
	this.add(lNao);
	this.add(jrbAdm);
	this.add(jrbMod);
	this.add(jrbDef);
	this.add(lTipo);
	this.add(lAdm);
	this.add(lMod);
	this.add(lDef);
	this.add(imagem2);
	this.add(lOutro);
	this.add(jrbOutro);
	this.add(scroll);
	
	this.setVisible(true);
	
}

int op = 0;
boolean checked, checked1;

public void actionPerformed(ActionEvent e) {

//-------------------INICIO DO BOTÃO INSERIR-------------------

	if(e.getSource() == btInserir){
		
		op = 1;
		
		txId.setEnabled(false);
		
		jrbAtivo1.setEnabled(false);
		jrbAtivo2.setEnabled(false);
		
		btAlterar.setEnabled(false);
		btExcluir.setEnabled(false);
		btInserir.setEnabled(false);
		btListar.setEnabled(false);
		btLocalizar.setEnabled(false);
		
	}

//-------------------FIM DO BOTÃO INSERIR-------------------

//-------------------INICIO DO BOTÃO LOCALIZAR-------------------

	if(e.getSource() == btLocalizar){
		
		op = 2;
		
		txId.setEnabled(true);
		taDescricao.setEnabled(false);
		txNome.setEnabled(false);
		
		jrbAdm.setEnabled(false);
		jrbAtivo1.setEnabled(false);
		jrbAtivo2.setEnabled(false);
		jrbDef.setEnabled(false);
		jrbMod.setEnabled(false);
		
		btAlterar.setEnabled(false);
		btExcluir.setEnabled(false);
		btInserir.setEnabled(false);
		btListar.setEnabled(false);
		btLocalizar.setEnabled(false);
		
	}

//-------------------FIM DO BOTÃO LOCALIZAR-------------------

//-------------------INICIO DE BOTÃO LISTAR-------------------

	if(e.getSource() == btListar){
		
		op = 3;
		
		txId.setEnabled(false);
		taDescricao.setEnabled(false);
		txNome.setEnabled(false);
		
		jrbAdm.setEnabled(false);
		jrbAtivo1.setEnabled(false);
		jrbAtivo2.setEnabled(false);
		jrbDef.setEnabled(false);
		jrbMod.setEnabled(false);
		
		btAlterar.setEnabled(false);
		btExcluir.setEnabled(false);
		btInserir.setEnabled(false);
		btListar.setEnabled(false);
		btLocalizar.setEnabled(false);
		
	}

//-------------------FIM DO BOTÃO LISTAR-------------------

//-------------------INICIO DO BOTÃO ALTERAR-------------------

	if(e.getSource() == btAlterar){
		
		op = 4;
		
		txId.setEnabled(false);
		taDescricao.setEnabled(true);
		txNome.setEnabled(true);
		
		jrbAdm.setEnabled(true);
		jrbAtivo1.setEnabled(true);
		jrbAtivo2.setEnabled(true);
		jrbDef.setEnabled(true);
		jrbMod.setEnabled(true);
		
		btAlterar.setEnabled(false);
		btExcluir.setEnabled(false);
		btInserir.setEnabled(false);
		btListar.setEnabled(false);
		btLocalizar.setEnabled(false);
		
	}

//-------------------FIM DO BOTÃO ALTERAR-------------------

//-------------------INICIO DO BOTÃO EXCLUIR-------------------

	if(e.getSource() == btExcluir){
		
		op = 5;
		
		txId.setEnabled(false);
		taDescricao.setEnabled(false);
		txNome.setEnabled(false);
		
		jrbAdm.setEnabled(false);
		jrbAtivo1.setEnabled(false);
		jrbAtivo2.setEnabled(false);
		jrbDef.setEnabled(false);
		jrbMod.setEnabled(false);
		
		btAlterar.setEnabled(false);
		btExcluir.setEnabled(false);
		btInserir.setEnabled(false);
		btListar.setEnabled(false);
		btLocalizar.setEnabled(false);
		
	}

//-------------------FIM DO BOTÃO EXCLUIR-------------------

//-------------------INICIO DO BOTÃO LIMPAR-------------------

	if(e.getSource() == btLimpar){
		
		op = 0;
		
		txId.setEnabled(true);
		taDescricao.setEnabled(true);
		txNome.setEnabled(true);
		
		jrbAdm.setEnabled(true);
		jrbAtivo1.setEnabled(true);
		jrbAtivo2.setEnabled(true);
		jrbDef.setEnabled(true);
		jrbMod.setEnabled(true);
		
		btAlterar.setEnabled(false);
		btExcluir.setEnabled(false);
		btInserir.setEnabled(true);
		btListar.setEnabled(true);
		btLocalizar.setEnabled(true);
		
		taDescricao.setText("");
		txId.setText("");
		txNome.setText("");
		
	}

//-------------------FIM DO BOTÃO LIMPAR-------------------

//-------------------INICIO DO BOTÃO SAIR-------------------

	if(e.getSource() == btSair){
		
		System.exit(0);
		
	}

//-------------------FIM DO BOTÃO SAIR-------------------

//-------------------iNICIO DO BOTÃO CONFIRMAR-------------------

	if(e.getSource() == btConfirmar){
	
	switch(op){

	//***ROTINA DE INSERÇÃO DE UM NOVO REGISTRO***
	
	case 1:
		
		//Le os campos do formulario e carrega o objeto aluno
		mid.setNome(txNome.getText());
		mid.setAtivo(1);
		
		checked = jrbAdm.isSelected();
		checked1 = jrbMod.isSelected();
		
		if(checked == true){
			
			mid.setTipo(0);
			
		}else{
			
			if(checked1 == true){
				
				mid.setTipo(1);
				
			}else{mid.setTipo(2);}
			
		}
		
		/*
		 * Passa o objeto aluno por parametro para o metodo Incluir
		 * do objeto conex (AlunoBD)
		 */
		conex.incluir(mid);
		
		JOptionPane.showMessageDialog(null, "Inclusão realizada com sucesso !!",
				"Confirmação", JOptionPane.INFORMATION_MESSAGE);break;
		
	//***FIM DA ROTINA DE INSERÇÃO DE UM NOVO REGISTRO***
	
	//***ROTINA DE CONSULTA DE UM REGISTRO
				
	case 2:			
		
		Midia midiaConsulta = new Midia();
		
		mid.setId(Integer.parseInt(txId.getText()));
		
		midiaConsulta = conex.consultar(mid);
		
		txNome.setText(midiaConsulta.getNome());
		
		boolean b = true;
		
		if(midiaConsulta.getTipo() == 0){
			
			jrbAdm.setSelected(b);
			
		}else{
			
			if(midiaConsulta.getTipo() == 1){
				
				jrbMod.setSelected(b);
				
			}else{jrbDef.setSelected(b);}
			
		}
		
		if(midiaConsulta.getAtivo() == 0){
			
			jrbAtivo2.setSelected(b);
			
		}else{
			
			jrbAtivo1.setSelected(b);
			btExcluir.setEnabled(true);
		
		}
		
		btAlterar.setEnabled(true);break;
	
	//***FIM DA ROTINA DE CONSULTA DE UM REGISTRO***
				
	//***ROTINA DE LISTAGEM DO BANCO***
		
	case 3:
		
		conex.listar();break;
		
	//***FIM DA ROTINA DE LISTAGEM DO BANCO***	
		
	//***ROTINA DE ALTERAÇÃO DE UM REGISTRO***
		
	case 4:
		
		mid.setNome(txNome.getText());
		
		boolean testeAdm = jrbAdm.isSelected();
		boolean testeMod = jrbMod.isSelected();
		
		if(testeAdm == true){
			
			mid.setTipo(0);
			
		}else{
			
			if(testeMod == true){
				
				mid.setTipo(1);
				
			}else{mid.setTipo(2);}}
			
		boolean testeAtivo = jrbAtivo1.isSelected();
		
		if(testeAtivo == true){
			
			mid.setAtivo(1);
			
		}else{mid.setAtivo(0);}

		
		conex.alterar(mid);
		
		JOptionPane.showMessageDialog(null, "Alteração realizada com sucesso!!",
				"Confirmação", JOptionPane.INFORMATION_MESSAGE);break;
				
	//***FIM DA ROTINA DE ALTERAÇÃO DE UM REGISTRO***	
				
	//***INICIO DA ROTINA DE EXCLUSÃO DE REGISTRO***
				
	case 5:
		
		int opcao = JOptionPane.showConfirmDialog(null,"Tem certaza que deseja excluir o registro?", "Alerta",JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION);  
		if(opcao == JOptionPane.YES_OPTION){
		
			mid.setAtivo(0);
			conex.excluir(mid);
			JOptionPane.showMessageDialog(null, "Registro excluido com sucesso!!","Comfirmação", JOptionPane.INFORMATION_MESSAGE);
			
			
			
		}else{JOptionPane.showMessageDialog(null, "Nenhum registro foi excluido!!","Comfirmação", JOptionPane.INFORMATION_MESSAGE);}break;
				
	//***FIM DA ROTINA DE EXCLUSÃO DE REGISTRO***		
		
	//***INICIO OPÇÃO PADRÃO***	
		
	default:
		
		JOptionPane.showMessageDialog(null, "Opção Inválida. \n\n Favor entrar com uma opção válida!!","Comfirmação", JOptionPane.INFORMATION_MESSAGE);break;
		
	//***FIM DA OPÇÃO PADRÃO***	
		
	}
	
}

//-------------------FIM DO BOTÃO CONFIRMAR-------------------

}

}
[/code]

Alguem tem alguma sugestão?

Que tal usar um plugin do Eclipse como o WindowBuilder , em vez de fazer as coisas no braço (e ainda por cima com null layout - argh)?

Vou dar daqui a pouquinho um exemplo bobo de JTextArea com JScrollPane, usando o WindowBuilder.

Vai ser uma boa, da uma olhada no meu código fonte pra ver qual é o erro que eu estou cometendo.

Estava dando uma pesquisada por ai e ouvi falar que que o JTextArea tem uma propriedade que da pra colocar uma barra vertical, da pra fazer mesmo ou é melhor colocar o JScrollPane.

package guj;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ExemploJTextAreaJScrollPane extends JFrame {
    private JScrollPane scrollPane;
    private JTextArea textArea;
    private JPanel pnlSouth;
    private JButton btnOk;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ExemploJTextAreaJScrollPane frame = new ExemploJTextAreaJScrollPane();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ExemploJTextAreaJScrollPane() {
        setTitle("Exemplo JScrollPane + JTextArea");
        setBounds(100, 100, 450, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(getScrollPane(), BorderLayout.CENTER);
        getContentPane().add(getPnlSouth(), BorderLayout.SOUTH);

    }

    private JScrollPane getScrollPane() {
        if (scrollPane == null) {
            scrollPane = new JScrollPane();
            scrollPane.setViewportView(getTextArea());
        }
        return scrollPane;
    }

    private JTextArea getTextArea() {
        if (textArea == null) {
            textArea = new JTextArea();
        }
        return textArea;
    }

    private JPanel getPnlSouth() {
        if (pnlSouth == null) {
            pnlSouth = new JPanel();
            pnlSouth.add(getBtnOk());
        }
        return pnlSouth;
    }

    private JButton getBtnOk() {
        if (btnOk == null) {
            btnOk = new JButton("OK");
            btnOk.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < 64; ++j) {
                        for (int i = 0; i < 10000; ++i) {
                            sb.append((char) ('@' + j));
                        }
                        sb.append('\r').append('\n');
                    }
                    getTextArea().setText(sb.toString());
                }
            });
        }
        return btnOk;
    }
}


O exemplo funcionou bem só que eu não estou conseguindo adapta-lo ao meu projeto, da alguns erros relacionados aos getContntPanes, getTextArea e getScrollPane, que eu não consigo resolver.

Sim, e é por isso que eu recomendo usar o WindowBuilder. Do jeito que você fez (totalmente na unha) é difícil programar.

    private JScrollPane getScrollPane() {  
        if (scrollPane == null) {  
            scrollPane = new JScrollPane();  
            scrollPane.setViewportView(getTextArea());  
        }  
        return scrollPane;  
    }  

Você entendeu como é que funciona o código gerado pelo WindowBuilder, a propósito?

Até onde entendi, cada componente é como um “atributo” declarado como privado e para acessa-lo é necessario um get ou set mas por serem objetos graficos sempre há retorno. Acho que é isso me corrija se eu estiver errado.