Label java перенос строки

Как написать текст на новой строке JLabel(java)

Все работает, но я не знаю как сделать, чтобы эта строчка писалась на новой строчке. \n не помогает.

Ответы (1 шт):

JLabel понимает html . Следовательно можно ему передать что то вроде:

label.setText("Строка1
Строка2");

К вопросу, «Как добавлять надписи в label в цикле, каждый раз с новой строки, при этом возможности сформировать сразу весь текст нет».

Что то вы странное изобретаете, но пожалуйста:

JLabel label = new JLabel(); label.setText("Line 1"); // где то позже в коде: for(int i = 0; i < 5; i++) < String currentText = label.getText(); // строка, без закрывающего тега String newText = currentText.substring(0, curentText.length()-7); label.setText(newText + "
New Line " + i + ""); >
import javax.swing.*; public class Test < public static void main(String s[]) < JFrame frame = new JFrame("JFrame Example"); JPanel panel = new JPanel(); JLabel label = new JLabel(); label.setText("Str1"); panel.add(label); frame.add(panel); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); for(int i = 0; i < 5; i++) < String currentText = label.getText(); String newText = currentText.substring(0, currentText.length()-7); label.setText(newText + "
New Line " + i + ""); > > >

Источник

How to add a newline to JLabel without using HTML

How can I add a new line to a JLabel ? I know if I use simple HTML, it will work. But if I use HTML, JLabel is not showing the font which embedded with the application. I am embedding the font using the method — createFont() and using JLabel.setFont() for applying the font.

6 Answers 6

SwingX supports multiline labels:

 JXLabel label = new JXLabel(); label.setLineWrap(true); 

Does JXLabel have the «right» baseline when using multiple lines of text? Note that «right» may mean different things to different people 😉

for me the correct baseline would be the baseline of the first character of the first line of the label. But I’m sure you could find other people who prefer a baseline centered on the whole height of the label for instance; other people may also want the baseline to be the baseline of the first character of the LAST line in the label. It actually depends how people want labels aligned in their layouts. I think my first suggestion makes sense the most.

I don’t think there is direct(and easy) way of doing JLabel with multiple lines without recurring to HTML. You can use JTextArea instead.

JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setOpaque(false); textArea.setBorder(BorderFactory.createEmptyBorder()); add(textArea, BorderLayout.CENTER); 

It should look almost the same. If you have different fonts for different components, you can add the following line to ensure that the font of JTextArea is the same with JLabel

textArea.setFont(UIManager.getFont("Label.font")); 

I am Embedding the font using the method — createFont() ) and using JLabel.setFont() for applying the font.

Instead try setting it in the HTML, as shown here.

From my viewpoitn, the main problem with using HTML is the loss of baseline, which most LayoutManagers are using nowadays (and that’s a good point IMHO)

JLabel is not originally intended for multiline text, from what I recall. You would need to override the various rendering methods to do the text line splitting manually.

Perhaps you should rather use a non-editable JTextArea if you want multiline labels.

1) if you want to Multiline JComponents without using JLabel, then you have to look for TextComponent as are JTextArea, JTextPane, JEditorPane, if should’t be editable then myTextComponent#setEditable(false);

Читайте также:  Read raw file python

2) I never see problem with Html & Font & Color in Swing, for example:

enter image description here

import java.awt.Color; import java.awt.Font; import javax.swing.*; public class ButtonFg extends JFrame < private static final long serialVersionUID = 1L; public ButtonFg() < JButton button = new JButton("- myText 
" + " - myText
" + " - myText
" + " - myText "); button.setForeground(Color.blue); button.setFont(new Font("Serif", Font.BOLD, 28)); button.setFocusPainted(false); add(button); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(150, 150); pack(); > public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < @Override public void run() < new ButtonFg().setVisible(true); >>); > >

Most of the following code is taken from BasicLabelUI and/or WindowsLabelUI but I added code to make it work with multiple lines. This was the minimum amount of copied code I could get to work. You can set the separator character between the lines with setSeparator or by changing the default on the instantiation of LinesAndIndex. I have not done extensive testing on this but it works for me so far. When using HTML the mnemonic did not work so I created this. If you have a better way to accomplish this please correct the code.

 import com.sun.java.swing.plaf.windows.WindowsLabelUI; import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.UIManager; import javax.swing.plaf.LabelUI; import javax.swing.plaf.basic.BasicGraphicsUtils; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.View; public class MultiLineLabelUI extends WindowsLabelUI < private static MultiLineLabelUI multiLineLabelUI; private LinesAndIndex lai = new LinesAndIndex(','); private Rectangle paintIconR = new Rectangle(); private Rectangle paintTextR = new Rectangle(); public static LabelUI createUI(JComponent c) < if (multiLineLabelUI == null) < multiLineLabelUI = new MultiLineLabelUI(); >return multiLineLabelUI; > private int getBaseline(JComponent c, int y, int ascent, int w, int h) < View view = (View) c.getClientProperty(BasicHTML.propertyKey); if (view != null) < int baseline = BasicHTML.getHTMLBaseline(view, w, h); if (baseline < 0) < return baseline; >return y + baseline; > return y + ascent; > public char getSeparator() < return lai.getSeparator(); >public void setSeparator(char ch) < lai.setSeparator(ch); >private String layout(JLabel label, FontMetrics fm, int width, int height, int lineCnt, int curLine, String text) < Insets insets = label.getInsets(null); Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); Rectangle paintViewR = new Rectangle(); paintViewR.width = width - (insets.left + insets.right); paintViewR.height = (height - (insets.top + insets.bottom)) / lineCnt; paintViewR.x = insets.left; paintViewR.y = insets.top + (paintViewR.height * curLine); paintIconR.x = 0; paintIconR.y = 0; paintIconR.width = 0; paintIconR.height = 0; paintTextR.x = 0; paintTextR.y = 0; paintTextR.width = 0; paintTextR.height = 0; return layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR); >protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY, int curLine) < int mnemonicIndex = lai.getMnemonicIndex(); // W2K Feature: Check to see if the Underscore should be rendered. if (WindowsLookAndFeel.isMnemonicHidden() == true) < mnemonicIndex = -1; >if (curLine != lai.getMnemonicLineIndex()) < mnemonicIndex = -1; >g.setColor(l.getForeground()); BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, textX, textY); > protected void paintDisabledText(JLabel l, Graphics g, String s, int textX, int textY, int curLine) < int mnemonicIndex = lai.getMnemonicIndex(); // W2K Feature: Check to see if the Underscore should be rendered. if (WindowsLookAndFeel.isMnemonicHidden() == true) < mnemonicIndex = -1; >if (curLine != lai.getMnemonicLineIndex()) < mnemonicIndex = -1; >if (UIManager.getColor("Label.disabledForeground") instanceof Color && UIManager.getColor("Label.disabledShadow") instanceof Color) < g.setColor(UIManager.getColor("Label.disabledShadow")); BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, textX + 1, textY + 1); g.setColor(UIManager.getColor("Label.disabledForeground")); BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, textX, textY); >else < Color background = l.getBackground(); g.setColor(background.brighter()); BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, textX + 1, textY + 1); g.setColor(background.darker()); BasicGraphicsUtils.drawStringUnderlineCharAt(g, s, mnemonicIndex, textX, textY); >> @Override public void paint(Graphics g, JComponent c) < JLabel label = (JLabel) c; String text = label.getText(); Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); if ((icon == null) && (text == null)) < return; >char mnemonic = (char) label.getDisplayedMnemonic(); lai.splitText(text, mnemonic); List lines = lai.getLines(); FontMetrics fm = label.getFontMetrics(g.getFont()); String[] clippedText = new String[lines.size()]; for (int i = 0; i < lines.size(); i++) < clippedText[i] = layout(label, fm, c.getWidth(), c.getHeight(), lines.size(), i, lines.get(i)); if (icon != null && i == 0) < icon.paintIcon(c, g, paintIconR.x, paintIconR.y); >if (text != null) < int textX = paintTextR.x; int textY = paintTextR.y + fm.getAscent(); if (label.isEnabled()) < paintEnabledText(label, g, clippedText[i], textX, textY, i); >else < paintDisabledText(label, g, clippedText[i], textX, textY, i); >> > > @Override public int getBaseline(JComponent c, int width, int height) < super.getBaseline(c, width, height); JLabel label = (JLabel) c; String text = label.getText(); if (text == null || "".equals(text) || label.getFont() == null) < return -1; >char mnemonic = (char) label.getDisplayedMnemonic(); lai.splitText(text, mnemonic); List lines = lai.getLines(); FontMetrics fm = label.getFontMetrics(label.getFont()); String[] clippedText = new String[lines.size()]; for (int i = 0; i < lines.size(); i++) < clippedText[i] = layout(label, fm, width, height, lines.size(), i, lines.get(i)); >return getBaseline(label, paintTextR.y, fm.getAscent(), paintTextR.width, paintTextR.height); > private static class LinesAndIndex < private char sep; private Listlines; private int mnemonicLineIndex; private int mnemonicIndex; LinesAndIndex(char sep) < mnemonicLineIndex = -1; mnemonicIndex = -1; lines = new ArrayList(); this.sep = sep; > public char getSeparator() < return sep; >public void setSeparator(char sep) < this.sep = sep; >public List getLines() < return lines; >public int getMnemonicLineIndex() < return mnemonicLineIndex; >public int getMnemonicIndex() < return mnemonicIndex; >public void splitText(String text, char mnemonic) < if (text == null) < return; >lines.clear(); mnemonicLineIndex = -1; mnemonicIndex = -1; char um = Character.toUpperCase(mnemonic); char lm = Character.toLowerCase(mnemonic); int umi = Integer.MAX_VALUE; int lmi = Integer.MAX_VALUE; int umli = -1; int lmli = -1; for (int i = 0, j = 0, k = 0; i < text.length(); i++) < if (text.charAt(i) == sep) < lines.add(text.substring(j, i)); j = i + 1; k++; >else if (text.charAt(i) == um) < if (umi == Integer.MAX_VALUE) < umi = i - j; umli = k; >> else if (text.charAt(i) == lm) < if (lmi == Integer.MAX_VALUE) < lmi = i - j; lmli = k; >> if (i == text.length() - 1) < lines.add(text.substring(j, i + 1)); >> mnemonicLineIndex = (lmi < umi) ? lmli : umli; mnemonicIndex = (lmi < umi) ? lmi : umi; >> > 

Источник

Читайте также:  Javascript поиск символов строки

JLabel выравнивание по ширине и перенос

Вообщем мне надо разместить текст на JLabel так что бы он автоматически ставил перенос в конце когда это необходимо, также что бы текст принимал максимальный возможный размер при этом не залезая за рамки ДЖИЛейбла, и выравнивание по центру.

Как отключить выравнивание JLabel?
Всем привет. У меня есть главное окно, наследовался от JFrame и я в него добавляю JLabel с.

Выравнивание по ширине
Как убрать большие разрывы между словами при выравнивании по ширине? Автоматическая расстановка.

Выравнивание по ширине
:friends:Дорогой всем. Очень нужны помогать как правильно только "Word.RTF" Вообще работа.

Выравнивание по ширине
Запарился уже делать пробелы тыкает только по нахождению первого пробела, а остальные слова.

В JLabel нет подобного функционала. Можно использовать JTextArea, поотключав всё ненужное. НО исчо могу предложить великолепный класс собственного написания, который на подобное способен (перенос по словам)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; public class Label extends JComponent { private static final long serialVersionUID = 1L; private String value; private Color color; private ListString> lines; public Label() { value = ""; } public Label(String text) { setText(text); } public void setText(String text) { if (text == null) { value = ""; } else { value = text; } } public String getText() { return value; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; if (color != null) { g2.setPaint(color); } lines = split(g2); FontRenderContext context = g2.getFontRenderContext(); Font font = g2.getFont(); Rectangle2D bounds = font.getStringBounds(lines.get(0), context); int x = 0; int y = 0; if (getAlignmentY() == CENTER_ALIGNMENT) { y += (int) (getHeight() - bounds.getHeight() * lines.size()) / 2; } else if (getAlignmentY() == BOTTOM_ALIGNMENT) { y += (int) (getHeight() - bounds.getHeight() * lines.size()); } for (int i = 0; i  lines.size(); i++) { bounds = font.getStringBounds(lines.get(i), context); if (getAlignmentX() == CENTER_ALIGNMENT) { x = (int) ((getWidth() - bounds.getWidth()) / 2); } else if (getAlignmentX() == RIGHT_ALIGNMENT) { x = (int) (getWidth() - bounds.getWidth()); } y += bounds.getHeight(); g2.drawString(lines.get(i), x, y); } } public ListString> split(Graphics2D g) { ArrayListString> lines = new ArrayList<>(); int prev = 0; for (int i = 0; i  value.length(); i++) { if (value.charAt(i) == '\n') { lines.add(value.substring(prev, i)); prev = i + 1; } } lines.add(value.substring(prev, value.length())); FontRenderContext context = g.getFontRenderContext(); Font font = g.getFont(); int limit = findMaxLength(value, font.getStringBounds(value, context).getWidth(), getWidth()); Rectangle2D bounds; String temp; for (int i = 0; i  lines.size(); i++) { temp = lines.get(i); bounds = font.getStringBounds(temp, context); if (bounds.getWidth() > getWidth()) { int j; for (j = limit; j > 0; j--) { if (Character.isWhitespace(temp.charAt(j))) { String leftPart = temp.substring(0, j); if (font.getStringBounds(leftPart, context).getWidth() > getWidth()) continue; lines.set(i, leftPart); lines.add(i + 1, temp.substring(j + 1)); break; } } if (j == 0) { int newLen = limit - 3; if (newLen = temp.length() && newLen >= 0) { temp = temp.substring(0, newLen).concat(". "); } lines.set(i, temp); } } } lines.trimToSize(); return lines; } public void setColor(Color color) { this.color = color; } public Color getColor() { return color; } private int findMaxLength(String str, double strWidth, double compWidth) { return (int) (compWidth / (strWidth / countVisibleCharacters(str))); } private int countVisibleCharacters(String s) { int count = 0; for (char c : s.toCharArray()) { if (!Character.isISOControl(c)) { count++; } } return count; } public Dimension getPreferredSize() { Graphics2D g = (Graphics2D) getGraphics(); FontRenderContext context = g.getFontRenderContext(); Rectangle2D bounds = g.getFont().getStringBounds(value, context); return new Dimension((int) bounds.getWidth(), (int) bounds.getHeight()); } public boolean equals(Object otherObject) { if (otherObject == this) { return true; } if (otherObject == null || getClass() != otherObject.getClass()) { return false; } Label other = (Label) otherObject; return value.equals(other.getText()); } public int hashCode() { return value.hashCode() * 17 + 2; } public String toString() { return "Label[text=\"" + value + "\"]"; } }

Источник

Оцените статью