Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display tab with spaces?

Tags:

java

tabs

swing

I have a java program where I draw each character(in its own frame) from text file on a JPanel with grid.

left- JPanel, right- text document Every character is in its own frame but when it comes to tabs there is a problem. I tried replacing all tabs with 8 spaces but the problem is (as seen on picture above) that it comes to inconsistency because tabs aren't always 8 chars long. Is there a way I can figure out how many "spaces" does a tab use? Or any other suggestions on how can I get the same layout as it is in text file?

code for 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);
    }
}
like image 420
komarkovich Avatar asked Jan 22 '26 14:01

komarkovich


1 Answers

You could check the length of the string before the tab.

In Al203 case, that would be 5. Your tab should begin at the next multiple of 8, with at least 1 space inbetween.

Here's a small class which could help you :

public class TabToSpaces
{
    public static void main(String[] args) {
        System.out.println(replaceTab("\tb", 8, "."));
        System.out.println(replaceTab("a\tb", 8, "."));
        System.out.println(replaceTab("abcdefg\th", 8, "."));
        System.out.println(replaceTab("abcdefgh\ti", 8, "."));
        System.out.println(replaceTab("a\tb\tc\td\te", 8, "."));
        System.out.println(replaceTab("ab\tb\tc\td\te", 8, "."));
    }

    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 used dots to make it clearer where the spaces are.

like image 152
Eric Duminil Avatar answered Jan 25 '26 04:01

Eric Duminil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!