如何计算JTextArea中的换行符数? 有一个简单的例子吗?有什么建议吗?
提前谢谢你!
答案 0 :(得分:0)
以下是来自this的程序:
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.text.*;
import javax.swing.*;
public class JTextAreaLineCountDemo extends JPanel {
JTextArea textArea;
static Font f = new Font("Helvetiva", Font.ITALIC, 50);
public JTextAreaLineCountDemo() {
super(new GridBagLayout());
String inputStr = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo, Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo";
textArea = new JTextArea(inputStr);
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
// Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(textArea, c);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent ce) {
**textArea.setFont(new Font("Arial", Font.BOLD, 22));**
System.out.println("Line count: " + countLines(textArea));
}
});
}
private static int countLines(JTextArea textArea) {
AttributedString text = new AttributedString(textArea.getText());
text.addAttribute(TextAttribute.FONT, f);
FontRenderContext frc = textArea.getFontMetrics(textArea.getFont())
.getFontRenderContext();
AttributedCharacterIterator charIt = text.getIterator();
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIt, frc);
float formatWidth = (float) textArea.getSize().width;
lineMeasurer.setPosition(charIt.getBeginIndex());
int noLines = 0;
while (lineMeasurer.getPosition() < charIt.getEndIndex()) {
lineMeasurer.nextLayout(formatWidth);
noLines++;
}
return noLines;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("JTextAreaLineCountDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTextAreaLineCountDemo());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}