JTextArea e barra de rolagem - dúvida

Fala galerinha do bem!!!
Aki, estou fazendo um programinha de cadastro de clientes onde recupero dados do meu database e um desses dados é de um JTextArea. Só que quando eu recupero esse dado ele ultrapassa o tamanho do textarea e não aparece as barras de rolagem. Já lí e relí vários posts daqui do fórum e de vários outros e ainda não consegui fazer meu código funcionar. Será que alguém pode me dar uma luz?
Desde Já agradeço. Segue meu código.

[code]
package cadastro;

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Rectangle;

import javax.swing.JTextArea;

public class index extends JFrame {

protected static JTextArea jTextArea = null;

public index() {
super();
initialize();
}

/**
 * This method initializes this
 * 
 * @return void
 */
private void initialize() {
	this.setSize(450, 450);
	this.setContentPane(getJContentPane());
	this.setResizable(false);
	this.setTitle("Cadastro de manutenções - JRFP Sistemas");
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	
}

private JPanel getJContentPane() {
	if (jContentPane == null) {

		jContentPane.add(getOrigem(), null);

}
return jContentPane;
}

private JTextArea getJTextArea() {
if (jTextArea == null) {
jTextArea = new JTextArea();
jTextArea.setBounds(new Rectangle(55, 225, 340, 120));
JScrollPane scroll = new JScrollPane(jTextArea);
jTextArea.setRows(20);
jTextArea.setColumns(20);
jTextArea.add(scroll);
jTextArea.getText();
}
return jTextArea;
}
}[/code]

Aki, já resolvi o problema e agora o texto aparece na linha de baixo. só que agora tem outro problema: quando ele passa pra linha de baixo ele quebra a palavra no meio!!! Alguém pode me ajudar?

Aí vai minha correção:

private JTextArea getJTextArea() { if (jTextArea == null) { jTextArea = new JTextArea(); jTextArea.setBounds(new Rectangle(55, 225, 340, 120)); jTextArea.setLineWrap(true); getContentPane().add(new JScrollPane(jTextArea), "Center"); jTextArea.getText(); } return jTextArea; }

Vlw!!!

Olá

Eu não te entendi bem quando disse que “quebra a palavra no meio”. Caso a palavra fica distribuída de tal maneira que ocupa toda a linha, deve ser porque o método “setLineWrap” possui “true” como argumento.

Exemplo de palavra cortada no meio:

Cooler com perda total. Instalado cooler novo. Valor da manut //aki a palavra quebra enção engloba mão-de-obra e cooler novo.

Vou tentar colocar false e escrevo de novo, mas se vc tiver alguma idéia agradeço muito.

Aki, tentei colocar false no setLineWrap mas continuou com o mesmo problema. :cry:

Será q mais alguém aí tem alguma idéia?

Vlw!!! :smiley:

Igor

Estou enviando um exemplo de código que utiliza um JTextArea embutido num JScrollPane. Para controlar a forma de apresentação do texto dentro do JTextArea utilizo o método setLineWrap. Se estiver true, o texto terá quebra de linha automática; se false, não será realizada a quebra de linha; Se o setLineWrap não for declarado, por default é considerado false.

import org.netbeans.lib.awtextra.AbsoluteConstraints;
import org.netbeans.lib.awtextra.AbsoluteLayout;

/**
 * @author  Éder
 */
public class Index2 extends javax.swing.JFrame{
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;

    public Index2() {
        initComponents();
    }
    
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

//* * * Preste atenção aqui * * *
//        jTextArea1.setLineWrap(true);
        jTextArea1.setText("BBBBBAAAAAAQualquer coisa deve ser escrita aqui, o importante \u00e9 que ocuope v\u00e1rias linhas entenderammmmmmmmmmmmmmmmmm");
//        jTextArea1.setLineWrap(false);
//* * * Ative e desative os setLineWrap
        
        jScrollPane1.setViewportView(jTextArea1);
        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 360));
        pack();
    }
    
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
    
    public static void main(String args[]) {
        new Index2().show();
    }
}

Esse código foi escrito no NetBeans 3.6. Se não tiveres as classes importadas, elas estão logo abaixo.

package org.netbeans.lib.awtextra;


/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

 

import java.awt.Dimension;
import java.awt.Point;

/** An object that encapsulates position and (optionally) size for
* Absolute positioning of components.
*
* @see AbsoluteLayout
* @version 1.01, Aug 19, 1998
*/
public class AbsoluteConstraints implements java.io.Serializable {
    /** generated Serialized Version UID */
    static final long serialVersionUID = 5261460716622152494L;

    /** The X position of the component */
    public int x;
    /** The Y position of the component */
    public int y;
    /** The width of the component or -1 if the component's preferred width should be used */
    public int width = -1;
    /** The height of the component or -1 if the component's preferred height should be used */
    public int height = -1;

    /** Creates a new AbsoluteConstraints for specified position.
    * @param pos The position to be represented by this AbsoluteConstraints
    */
    public AbsoluteConstraints(Point pos) {
        this (pos.x, pos.y);
    }

    /** Creates a new AbsoluteConstraints for specified position.
    * @param x The X position to be represented by this AbsoluteConstraints
    * @param y The Y position to be represented by this AbsoluteConstraints
    */
    public AbsoluteConstraints(int x, int y) {
        this.x = x;
        this.y = y;
    }

    /** Creates a new AbsoluteConstraints for specified position and size.
    * @param pos  The position to be represented by this AbsoluteConstraints
    * @param size The size to be represented by this AbsoluteConstraints or null
    *             if the component's preferred size should be used
    */
    public AbsoluteConstraints(Point pos, Dimension size) {
        this.x = pos.x;
        this.y = pos.y;
        if (size != null) {
            this.width = size.width;
            this.height = size.height;
        }
    }

    /** Creates a new AbsoluteConstraints for specified position and size.
    * @param x      The X position to be represented by this AbsoluteConstraints
    * @param y      The Y position to be represented by this AbsoluteConstraints
    * @param width  The width to be represented by this AbsoluteConstraints or -1 if the 
    *               component's preferred width should be used  
    * @param height The height to be represented by this AbsoluteConstraints or -1 if the
    *               component's preferred height should be used  
    */
    public AbsoluteConstraints(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    /** @return The X position represented by this AbsoluteConstraints */
    public int getX () {
        return x;
    }

    /** @return The Y position represented by this AbsoluteConstraints */
    public int getY () {
        return y;
    }

    /** @return The width represented by this AbsoluteConstraints or -1 if the
    * component's preferred width should be used 
    */
    public int getWidth () {
        return width;
    }

    /** @return The height represented by this AbsoluteConstraints or -1 if the
    * component's preferred height should be used 
    */
    public int getHeight () {
        return height;
    }

    public String toString () {
        return super.toString () +" [x="+x+", y="+y+", width="+width+", height="+height+"]";
    }

}
package org.netbeans.lib.awtextra;


/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

 

import java.awt.*;

/** AbsoluteLayout is a LayoutManager that works as a replacement for "null" layout to
* allow placement of components in absolute positions.
*
* @see AbsoluteConstraints
* @version 1.01, Aug 19, 1998
*/
public class AbsoluteLayout implements LayoutManager2, java.io.Serializable {
    /** generated Serialized Version UID */
    static final long serialVersionUID = -1919857869177070440L;

    /** Adds the specified component with the specified name to
    * the layout.
    * @param name the component name
    * @param comp the component to be added
    */
    public void addLayoutComponent(String name, Component comp) {
        throw new IllegalArgumentException();
    }

    /** Removes the specified component from the layout.
    * @param comp the component to be removed
    */
    public void removeLayoutComponent(Component comp) {
        constraints.remove(comp);
    }

    /** Calculates the preferred dimension for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    *
    * @see #minimumLayoutSize
    */
    public Dimension preferredLayoutSize(Container parent) {
        int maxWidth = 0;
        int maxHeight = 0;
        for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();) {
            Component comp = (Component)e.nextElement();
            AbsoluteConstraints ac = (AbsoluteConstraints)constraints.get(comp);
            Dimension size = comp.getPreferredSize();

            int width = ac.getWidth ();
            if (width == -1) width = size.width;
            int height = ac.getHeight ();
            if (height == -1) height = size.height;

            if (ac.x + width > maxWidth)
                maxWidth = ac.x + width;
            if (ac.y + height > maxHeight)
                maxHeight = ac.y + height;
        }
        return new Dimension (maxWidth, maxHeight);
    }

    /** Calculates the minimum dimension for the specified
    * panel given the components in the specified parent container.
    * @param parent the component to be laid out
    * @see #preferredLayoutSize
    */
    public Dimension minimumLayoutSize(Container parent) {
        int maxWidth = 0;
        int maxHeight = 0;
        for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();) {
            Component comp = (Component)e.nextElement();
            AbsoluteConstraints ac = (AbsoluteConstraints)constraints.get(comp);

            Dimension size = comp.getMinimumSize();

            int width = ac.getWidth ();
            if (width == -1) width = size.width;
            int height = ac.getHeight ();
            if (height == -1) height = size.height;

            if (ac.x + width > maxWidth)
                maxWidth = ac.x + width;
            if (ac.y + height > maxHeight)
                maxHeight = ac.y + height;
        }
        return new Dimension (maxWidth, maxHeight);
    }

    /** Lays out the container in the specified panel.
    * @param parent the component which needs to be laid out
    */
    public void layoutContainer(Container parent) {
        for (java.util.Enumeration e = constraints.keys(); e.hasMoreElements();) {
            Component comp = (Component)e.nextElement();
            AbsoluteConstraints ac = (AbsoluteConstraints)constraints.get(comp);
            Dimension size = comp.getPreferredSize();
            int width = ac.getWidth ();
            if (width == -1) width = size.width;
            int height = ac.getHeight ();
            if (height == -1) height = size.height;

            comp.setBounds(ac.x, ac.y, width, height);
        }
    }

    /** Adds the specified component to the layout, using the specified
    * constraint object.
    * @param comp the component to be added
    * @param constr  where/how the component is added to the layout.
    */
    public void addLayoutComponent(Component comp, Object constr) {
        if (!(constr instanceof AbsoluteConstraints))
            throw new IllegalArgumentException();
        constraints.put(comp, constr);
    }

    /** Returns the maximum size of this component.
    * @see java.awt.Component#getMinimumSize()
    * @see java.awt.Component#getPreferredSize()
    * @see LayoutManager
    */
    public Dimension maximumLayoutSize(Container target) {
        return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
    }

    /** Returns the alignment along the x axis.  This specifies how
    * the component would like to be aligned relative to other
    * components.  The value should be a number between 0 and 1
    * where 0 represents alignment along the origin, 1 is aligned
    * the furthest away from the origin, 0.5 is centered, etc.
    */
    public float getLayoutAlignmentX(Container target) {
        return 0;
    }

    /** Returns the alignment along the y axis.  This specifies how
    * the component would like to be aligned relative to other
    * components.  The value should be a number between 0 and 1
    * where 0 represents alignment along the origin, 1 is aligned
    * the furthest away from the origin, 0.5 is centered, etc.
    */
    public float getLayoutAlignmentY(Container target) {
        return 0;
    }

    /** Invalidates the layout, indicating that if the layout manager
    * has cached information it should be discarded.
    */
    public void invalidateLayout(Container target) {
    }


    /** A mapping <Component, AbsoluteConstraints> */
    protected java.util.Hashtable constraints = new java.util.Hashtable();
}

O que eu posso ajudar está aí.
Boa sorte…

Muito obrigado a todos. Usei os exemplos de todo mundo e meu JTextArea ficou assim:

[code]JTextArea jTextArea = new JTextArea(); // novo JTextArea

private JScrollPane getJScrollPane() {
if (jScrollPane == null) { // jScrollPane já declarado no meu jContentPane
jScrollPane = new JScrollPane(jTextArea); jTextArea dentro do JScrollPane
jScrollPane.setBounds(new Rectangle(53, 187, 361, 133)); // tamanho do jScrollPane
jScrollPane.setVerticalScrollBarPolicy(jScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); // só mostra a barra vertical se necessário
jScrollPane.setHorizontalScrollBarPolicy(jScrollPane.HORIZONTAL_SCROLLBAR_NEVER); // nunca mostra a barra de rolagem horizontal
jTextArea.setWrapStyleWord(true);
jTextArea.setLineWrap(true); // quebra a linha
jTextArea.getText();
}
return jScrollPane; // retorna o jScrollPane
}
[/code]

Espero ajudar alguém aí!!!
Flw!!!

1 curtida