2009-06-26 14 views
8

Quiero crear un cuadro de diálogo que contenga algún tipo de elemento de texto (JLabel/JTextArea, etc.) que tenga varias líneas y ajuste las palabras. Quiero que el cuadro de diálogo tenga un ancho fijo, pero adapte la altura según el tamaño del texto. Tengo este código:Obtener la altura del texto de varias líneas con ancho fijo para hacer que el tamaño del diálogo sea correcto

import static javax.swing.GroupLayout.DEFAULT_SIZE; 

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

import javax.swing.*; 

public class TextSizeProblem extends JFrame { 
    public TextSizeProblem() { 

    String dummyString = ""; 
    for (int i = 0; i < 100; i++) { 
     dummyString += " word" + i; //Create a long text 
    } 
    JLabel text = new JLabel(); 
    text.setText("<html>" + dummyString + "</html>"); 

    JButton packMeButton = new JButton("pack"); 
    packMeButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
     pack(); 
     } 
    }); 

    GroupLayout layout = new GroupLayout(this.getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setVerticalGroup(layout.createParallelGroup() 
     .addComponent(packMeButton) 
     .addComponent(text) 
    ); 
    layout.setHorizontalGroup(layout.createSequentialGroup() 
     .addComponent(packMeButton) 
     .addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400 
    ); 

    pack(); 
    } 

    public static void main(String args[]) { 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
     JFrame frame = new TextSizeProblem(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     } 
    }); 
    } 
} 

Cuando se ejecuta el programa se ve así: alt text http://lesc.se/stackoverflow/multiline_size_1.png

Pero me gustaría que el diálogo con el siguiente aspecto (como cuando se pulsa el botón de paquete): alt text http://lesc.se/stackoverflow/multiline_size_2.png

Supongo que el problema es que el administrador de diseño no ha podido determinar la altura correcta del texto antes de mostrarlo en la pantalla. He intentado varios validate(), invalidate(), validateTree() etc. pero no he tenido éxito.

Respuesta

4

he encontrado una solución a mi problema. Al reemplazar el JLabel con un JTextArea:

JTextArea text = new JTextArea(); 
text.setText(dummyString); 
text.setLineWrap(true); 
text.setWrapStyleWord(true); 

Y llamando pack() seguido de una invocación al controlador de distribución a la disposición de los componentes de nuevo seguido de otro paquete:

pack(); 
layout.invalidateLayout(this.getContentPane()); 
pack(); 

Esto hará que el administrador de diseño se adapte al ancho.

El código completo:

import static javax.swing.GroupLayout.DEFAULT_SIZE; 

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

import javax.swing.*; 

public class TextSizeProblem3 extends JFrame { 
    public TextSizeProblem3() { 

    String dummyString = ""; 
    for (int i = 0; i < 100; i++) { 
     dummyString += " word" + i; //Create a long text 
    } 
    JTextArea text = new JTextArea(); 
    text.setText(dummyString); 
    text.setLineWrap(true); 
    text.setWrapStyleWord(true); 

    JButton packMeButton = new JButton("pack"); 
    packMeButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
     pack(); 
     } 
    }); 

    GroupLayout layout = new GroupLayout(this.getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setVerticalGroup(layout.createParallelGroup() 
     .addComponent(packMeButton) 
     .addComponent(text) 
    ); 
    layout.setHorizontalGroup(layout.createSequentialGroup() 
     .addComponent(packMeButton) 
     .addComponent(text, DEFAULT_SIZE, 400, 400) //Lock the width to 400 
    ); 

    pack(); 
    layout.invalidateLayout(this.getContentPane()); 
    pack(); 
    } 

    public static void main(String args[]) { 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
     JFrame frame = new TextSizeProblem3(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     } 
    }); 
    } 
} 

(se puede añadir un poco de personalización (borde, color, etc) por lo que se parece a la JLabel pero han omitido eso)

+0

¿Rinde etiquetas HTML? ¡No! – Soley

10

Aquí hay una adaptación de su código, haciendo lo que quiera. Pero se necesita un pequeño truco para calcular el tamaño de la etiqueta y establecer su tamaño preferido.

I found the solution here

import static javax.swing.GroupLayout.DEFAULT_SIZE; 

import java.awt.Dimension; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.*; 
import javax.swing.text.View; 

public class TextSizeProblem extends JFrame { 
    public TextSizeProblem() { 

     String dummyString = ""; 
     for (int i = 0; i < 100; i++) { 
      dummyString += " word" + i; // Create a long text 
     } 
     JLabel text = new JLabel(); 
     text.setText("<html>" + dummyString + "</html>"); 

     Dimension prefSize = getPreferredSize(text.getText(), true, 400); 

     JButton packMeButton = new JButton("pack"); 
     packMeButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       pack(); 
      } 
     }); 



     GroupLayout layout = new GroupLayout(this.getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setVerticalGroup(layout.createParallelGroup().addComponent(packMeButton) 
       .addComponent(text,DEFAULT_SIZE, prefSize.height, prefSize.height)); 
     layout.setHorizontalGroup(layout.createSequentialGroup().addComponent(packMeButton) 
       .addComponent(text, DEFAULT_SIZE, prefSize.width, prefSize.width) // Lock the width to 400 
       ); 

     pack(); 
    } 

    public static void main(String args[]) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame frame = new TextSizeProblem(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    private static final JLabel resizer = new JLabel(); 

    /** 
    * Returns the preferred size to set a component at in order to render an html string. You can 
    * specify the size of one dimension. 
    */ 
    public static java.awt.Dimension getPreferredSize(String html, boolean width, int prefSize) { 

     resizer.setText(html); 

     View view = (View) resizer.getClientProperty(javax.swing.plaf.basic.BasicHTML.propertyKey); 

     view.setSize(width ? prefSize : 0, width ? 0 : prefSize); 

     float w = view.getPreferredSpan(View.X_AXIS); 
     float h = view.getPreferredSpan(View.Y_AXIS); 

     return new java.awt.Dimension((int) Math.ceil(w), (int) Math.ceil(h)); 
    } 
} 
+0

Sí, esta solución funciona! –

+0

Dios desearía poder votar este tiempo Ton. – Burimi

5

Creo que esto es lo que quiere:

JLabel label = new JLabel("<html><div style=\"width:200px;\">Lots of text here...</div></html>"); 
// add the label to some Container. 

Esto restringirá la JLabel a ser de 200 píxeles de ancho y ajustar automáticamente la altura para ajustar el texto.

+0

Vea un ejemplo en [LabelRenderTest.java] (http://stackoverflow.com/questions/5853879/java-swing-obtain-image-of-jframe/5853992#5853992) (mostrado arriba). –

Cuestiones relacionadas