txt salto línea linea espacio comparar brinco java user-interface swing jlabel

linea - Java: ¿Los saltos de línea en JLabels?



settext salto de linea (7)

¿Qué pasa con el uso de la función de ajuste en un JTextArea?

String text = "some really long string that might need to"+ "be wrapped if the window is not wide enough"; JTextArea multi = new JTextArea(text); multi.setWrapStyleWord(true); multi.setLineWrap(true); multi.setEditable(false); JLabel single = new JLabel(text); JPanel textpanel = new JPanel(new GridLayout(2,1)); textpanel.add(multi); textpanel.add(single); JFrame frame = new JFrame(); frame.add(textpanel); frame.pack(); frame.setVisible(true);

Estoy tratando de hacer un Swing JLabel con varias líneas de texto. Se agregó muy bien, pero los saltos de línea no se cumplen. ¿Cómo hago esto? Alternativamente, ¿puedo especificar un ancho máximo para un JLabel y saber que el texto se ajustará, como en un div?

private void addLegend() { JPanel comparisonPanel = getComparisonPanel(); //this all displays on one line JLabel legend = new JLabel("MMM FFF MMM FFFO O OOM M MMMM./nMMM FFF MMM FFFO O OOM M MMMM./nMMM FFF MMM FFFO O OOM M MMMM./n"); comparisonPanel.add(legend); }


No logré especificar un ancho máximo para una etiqueta, pero puede especificar un ancho concreto. Al medir el ancho actual de un JLabel solo podemos aplicar el nuevo fijo con si el ancho de JLabels es mayor que nuestro maxWidth:

JLabel label = new JLabel("<html>" + myVeryLongMessage + "<html>"); int maxWidth = 400; Dimension size = label.getPreferredSize(); if (size.width > maxWidth) { // Estimate the number of lines int lineCount = (int) Math.ceil(((double) size.width) / maxWidth); lineCount += 1; // Add one extra line as reserve size.width = maxWidth; // Apply the maximum width // Increase the height so that all lines will be visible size.height *= lineCount; label.setPreferredSize(size); }


Por defecto, Swing no ajusta el texto. Si especifica un tamaño en JLabel, solo pintará la parte del texto que se ajuste y luego agregará "..." al final.

Como se sugiere, puede utilizar HTML para habilitar el ajuste de línea. Sin embargo, en realidad he creado un delegado de Swing UI no hace mucho tiempo para lograr esto y aún más: MultiLineLabelUI .

Envolverá el texto para que se ajuste al espacio disponible y también respete los saltos de línea. Si eliges probarlo, es tan simple como:

JLabel label = new JLabel("Text that''ll wrap if necessary"); label.setUI(MultiLineLabelUI.labelUI);

O, alternativamente, use la clase personalizada MultiLineLabel que, además de ajustar el texto, admite la alineación vertical y horizontal del texto.

ACTUALIZAR

Perdí el dominio con las muestras de código originales. Ahora puede verse en github en su lugar: MultiLineLabelUI


Puede obtener un salto de línea automático si configura el ancho del párrafo en html.

label.setText("<html><p style=/"width:100px/">"+paragraph+"</p></html>");


Puedes poner HTML dentro de un JLabel y usar la etiqueta linebreak para lograr esto.


Simple, utiliza HTML. Aunque los componentes de Java Swing no proporcionan un soporte "fantástico" para el HTML, puede usarlo para propósitos tan simples.

label.setText("<html>This is first line.<br/>This is second line.</html>");


Usa HTML en setText, por ejemplo

myLabel.setText("<html><body>with<br>linebreak</body></html>");