Como quebrar a string

Olá!

Bem…eu to pegando um String do banco e mostrando na tela, porém esta String, etá muito grande e não cabe em linha reta na tela do computador! Eu precisava dar um \n no meio dessa String do banco para poder quebrá-la. Como posso fazer isso? Afinal…o que eu tenho é um rs.getString(“endereco”), por exemplo.

Valeu…

eu diria q o seu problema não é com a String, mas sim com a sua apresentação… é Swing? com certeza o componente tem uma opção que quebra a String pra vc automaticamente qnd termina o espaço ao invéz de adicionar scroll

Estou imprimindo em um JLabel!

Por exemplo:

meujlabel.setText(rs.getString(“nome”));

Valeu…

ahhhhhhhhhh… saquei, bem, nesse caso, eu faria um método onde eu passo a String do label, esse método contava quantos caracters ela tem, se ultrapassar X caracters (largura do label), coloca um \n na String… algo assim eu imagino

[quote]com certeza o componente tem uma opção que quebra a String pra vc automaticamente qnd termina o espaço ao invéz de adicionar scroll
[/quote]

Como faz isso? Com um JTextArea, por exemplo?

[quote=“Schuenemann”][quote]com certeza o componente tem uma opção que quebra a String pra vc automaticamente qnd termina o espaço ao invéz de adicionar scroll
[/quote]

Como faz isso? Com um JTextArea, por exemplo?[/quote]

ahh não sei, não sou programador swing… hehehe, mas ja vi algo assim :lol:

Se vc quiser fazer um negocio profissional, além de aprender um pouco mais, utilize a classe FontMetrics pra calcular a largura da tua String em pixels e depois separa-la em quantas linhas forem necessárias…

[quote=“Schuenemann”][quote]com certeza o componente tem uma opção que quebra a String pra vc automaticamente qnd termina o espaço ao invéz de adicionar scroll
[/quote]

Como faz isso? Com um JTextArea, por exemplo?[/quote]

cara, dá uma olhada aqui… acho que tem alguma coisa parecida…

eu tb naum sou bom em Swing… hehehe

http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html

Tá, mas como eu faria para colocar um \n no meio de minha String?

Não esqueçam que eu só tenho isso String s = rs.getString(“nome”);

[quote]Tá, mas como eu faria para colocar um \n no meio de minha String?

Não esqueçam que eu só tenho isso String s = rs.getString(“nome”);[/quote]

Usa substring. Por exemplo:

s1 = s.substring(0, x) + "\n"; s2 = s.substring(x+1, s.length()-1);

Você trabalha só com J2EE?

[quote]cara, dá uma olhada aqui… acho que tem alguma coisa parecida…

eu tb naum sou bom em Swing… hehehe

http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html[/quote]
Funciona legal, só falta algo pra justificar :grin:

Talvez usando FontMetrics como o viecili falou.

[quote=“Schuenemann”]ahh não sei, não sou programador swing.. hehehe, mas ja vi algo assim

Você trabalha só com J2EE?

[code]cara, dá uma olhada aqui… acho que tem alguma coisa parecida…

eu tb naum sou bom em Swing… hehehe

http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html[/code]

Funciona legal, só falta algo pra justificar :grin:

Talvez usando FontMetrics como o viecili falou.[/quote]

Sim, eu trabalho com J2EE, mas como estamos fazendo o sistema em intranet, naum estamos utilizado swing.

Ae Schuenemann…
Não entendi isto que tu fez…o que é o “x”?

Comenta aquelas linhas, por favor!

[quote=“Schuenemann”]
Usa substring. Por exemplo:

s1 = s.substring(0, x) + "\n"; s2 = s.substring(x+1, s.length()-1);[/quote]

assim vc ficará sem os caracteres da posição x e s.lenght()-1

o correto seria assim:

s1 = s.substring(0, x) + "\n"; s2 = s.substring(x, s.length());

substring(x,y) => x inclusive, y exclusive

Você tem a string “PortalJava” (tirei o espaço pra ficar mais fácil de entender), e quer que no JLabel apareça cada palavra numa linha, certo?

String pj = "PortalJava"; String portal = pj.substring(0, 5); String java = pj.substring(6, 9); pj = portal + "\n" + java; // Cada palavra em uma linha

Se for pra quebrar exatamente no meio, faz algo do tipo:

String pj = "PortalJava"; int x = pj.length() / 2; String s1 = pj.substring(0, x - 1); String s2 = pj.substring(x, pj.length() - 1); pj = s1 + "\n" + s2;

E o label.setText(pj) no final.


Ahh sim, tem o detalhe que o cara falou aí. O intervalo é [x,y) :slight_smile:

Fiquei curioso pra ver como funcionaria com FontMetrics e fiz o seguinte Frame: (o código está implementado no método jButton1ActionPerformed)

[code]/*

  • FontMetricsFrame.java
  • Created on 13 de Janeiro de 2005, 17:36
    */

package testefontmetrics;

import java.awt.FontMetrics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

/**
*

  • @author viecili
    */
    public class FontMetricsFrame extends javax.swing.JFrame {

    /** Creates new form FontMetricsFrame */
    public FontMetricsFrame() {
    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.
      */
      private void initComponents() {
      jLabel1 = new javax.swing.JLabel();
      labelLarg = new javax.swing.JLabel();
      labelAlt = new javax.swing.JLabel();
      labelText = new javax.swing.JLabel();
      jTextField1 = new javax.swing.JTextField();
      jTextField2 = new javax.swing.JTextField();
      jScrollPane1 = new javax.swing.JScrollPane();
      jTextArea1 = new javax.swing.JTextArea();
      jButton1 = new javax.swing.JButton();

      getContentPane().setLayout(null);

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setTitle("FontMetrics Test");
      jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
      jLabel1.setText("jLabel1");
      jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
      jLabel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
      getContentPane().add(jLabel1);
      jLabel1.setBounds(10, 170, 380, 20);

      labelLarg.setText("Largura");
      getContentPane().add(labelLarg);
      labelLarg.setBounds(10, 10, 60, 20);

      labelAlt.setText("Altura");
      getContentPane().add(labelAlt);
      labelAlt.setBounds(10, 30, 60, 20);

      labelText.setText("Texto");
      getContentPane().add(labelText);
      labelText.setBounds(10, 50, 60, 20);

      jTextField1.setFont(new java.awt.Font("MS Sans Serif", 0, 10));
      jTextField1.setText(String.valueOf(jLabel1.getBounds().getWidth()));
      jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
      jTextField1FocusLost(evt);
      }
      });

      getContentPane().add(jTextField1);
      jTextField1.setBounds(70, 10, 80, 20);

      jTextField2.setFont(new java.awt.Font("MS Sans Serif", 0, 10));
      jTextField2.setText(String.valueOf(jLabel1.getBounds().getHeight()));
      jTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
      jTextField2FocusLost(evt);
      }
      });

      getContentPane().add(jTextField2);
      jTextField2.setBounds(70, 30, 80, 19);

      jTextArea1.setText(jLabel1.getText());
      jScrollPane1.setViewportView(jTextArea1);

      getContentPane().add(jScrollPane1);
      jScrollPane1.setBounds(70, 50, 320, 80);

      jButton1.setText("Vai !");
      jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      jButton1ActionPerformed(evt);
      }
      });

      getContentPane().add(jButton1);
      jButton1.setBounds(320, 140, 71, 23);

      java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
      setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);
      }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    // ajustar o texto no label
    StringBuffer texto = new StringBuffer("");
    String[] palavras = jTextArea1.getText().split(" ");
    FontMetrics fm = jLabel1.getFontMetrics(jLabel1.getFont());
    Rectangle b = jLabel1.getBounds();
    int larg = (int) b.getWidth();
    StringBuffer linha = new StringBuffer("");
    int sw = 0;
    if (palavras.length <= 1) {
    jLabel1.setText(jTextArea1.getText());
    repaint();
    return;
    }
    for (int i = 0; i < palavras.length; i++) {
    String l = (linha.toString()+" "+palavras[i]);
    sw = fm.stringWidth(l);
    if (larg < sw) { // não coube
    texto.append(linha.toString()+"\n");
    linha = new StringBuffer(palavras[i]);
    } else if (larg == sw) { // coube certinho
    texto.append(l+"\n");
    linha = new StringBuffer("");
    } else { // cabe mais
    if (linha.length() == 0) {
    linha.append(palavras[i]);
    } else {
    linha.append(" "+palavras[i]);
    }
    }
    }
    if (linha.length() > 0) {
    texto.append(linha);
    } else {
    texto.deleteCharAt(texto.length()-1);
    }
    Rectangle2D sb = fm.getStringBounds(texto.toString(), null);
    Insets iset = jLabel1.getInsets();
    jLabel1.setBounds(10, 170, (int) sb.getWidth() + iset.left + iset.right, (int) sb.getHeight() + iset.top + iset.bottom);
    jLabel1.setText(texto.toString());
    jTextArea1.setText(texto.toString());
    mostraDimensao();
    repaint();
    }

    private void jTextField2FocusLost(java.awt.event.FocusEvent evt) {
    // TODO add your handling code here:
    // redimensionar a altura
    ajustaLabel();
    }

    private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {
    // TODO add your handling code here:
    // redimensionar a largura
    ajustaLabel();
    }

    private void ajustaLabel() {
    jLabel1.setBounds(10,170, (int) Double.parseDouble((jTextField1.getText())), (int) Double.parseDouble((jTextField2.getText())));
    repaint();
    }

    private void mostraDimensao() {
    jTextField1.setText(String.valueOf(jLabel1.getBounds().getWidth()));
    jTextField2.setText(String.valueOf(jLabel1.getBounds().getHeight()));
    }
    /**

    • @param args the command line arguments
      */
      public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new FontMetricsFrame().setVisible(true);
      }
      });
      }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JLabel labelAlt;
    private javax.swing.JLabel labelLarg;
    private javax.swing.JLabel labelText;
    // End of variables declaration

}[/code]

E descobri que o Label só pode ter uma linha, não adianta colocar “\n” que ele vai desenhar tudo numa linha só :cry: :evil:

Huahuahuahuahua…isso mesmo hehehehe! Para um JTextField é a mesma coisa tbm!
É que tipo…lógicamente isto era pra ser óbvio…é como tu declarar uma linha e querer escrever em duas…não dá né!
Eu também tive que tentar de tudo que era jeito, até descobrir que não tem como hehehe abraço velho!

[quote]Huahuahuahuahua…isso mesmo hehehehe! Para um JTextField é a mesma coisa tbm!
É que tipo…lógicamente isto era pra ser óbvio…é como tu declarar uma linha e querer escrever em duas…não dá né!
Eu também tive que tentar de tudo que era jeito, até descobrir que não tem como hehehe abraço velho![/quote]

Talvez 2 JLabel? 8O

foi com JLabel que eu fiz! não adianta…

pensei numas saídas: (toscas, mas são saídas) :idea: :roll:

  1. colocar um JTextArea e ajustar as propriedades visuais e de edição para que ele pareça um JLabel
  2. colocar cada linha em JLabel’s distintos dinamicamente, e posicioná-los um embaixo do outro