How do I display tabs with spaces?
•
Java
I have a java program that draws each character (in its own frame) from a text file on a JPanel with a grid
Code of drawing text:
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Font font = new Font("monospaced",Font.PLAIN,18); g2.setColor(Color.BLACK); g2.setFont(font); String lines[] = LabAgentComponent.PASTE.split("\\r?\\n"); for (int i=0; i<lines.length; i++) { for(int j=0; j<lines[i].length(); j++) { g2.drawString(Character.toString(lines[i].charAt(j)),j * gridSize,(i+1) * gridSize); } }
Solution
You can check the length of the string before the tab
In the case of Al203, that would be 5 Your label should start with the next multiple of 8 with at least one space between them
This is a small class that can help you:
public class TabToSpaces { public static void main(String[] args) { System.out.println(replaceTab("\tb",8,".")); System.out.println(replaceTab("a\tb",".")); System.out.println(replaceTab("abcdefg\th",".")); System.out.println(replaceTab("abcdefgh\ti",".")); System.out.println(replaceTab("a\tb\tc\td\te",".")); System.out.println(replaceTab("ab\tb\tc\td\te",".")); } private static String replaceTab(String string,int tabSize,String space) { Pattern pattern = Pattern.compile("\t"); Matcher matcher = pattern.matcher(string); StringBuffer sb = new StringBuffer(); int offset = 0; while (matcher.find()) { int beforeLength = matcher.start() + offset; int spacesNeeded = (int) (Math.ceil((beforeLength + 1.0) / tabSize) * tabSize) - beforeLength; offset += spacesNeeded - 1; String spaces = new String(new char[spacesNeeded]).replace("\0",space); matcher.appendReplacement(sb,spaces); } matcher.appendTail(sb); return sb.toString(); } }
It outputs:
........b a.......b abcdefg.h abcdefgh........i a.......b.......c.......d.......e ab......b.......c.......d.......e
I use dots to make the space clearer
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码