gpt4 book ai didi

java - Java Swing JeditorPane 中的自动缩进括号

转载 作者:行者123 更新时间:2023-11-30 08:06:37 25 4
gpt4 key购买 nike

我正在java中开发一个代码编辑器,我想知道如何像实际的代码编辑器一样使用括号(打开和关闭)自动缩进。

像这样1:

Array PrincipalVar = (Var => (OtherVar =>  (var3 => 3,
var4 => 8,
var6 => 1)
),
Var2 => (var => 1))

编辑器是一个 JEditorPane。我尝试了一些代码,但似乎没有任何效果。我已经有文件内容代码,并且我想重新缩进该文件。我已经尝试过的代码:

public String indentFileTry() throws FileNotFoundException{
LinkedList<Integer> inBracket = new LinkedList<Integer>();
String currentLine = "";
Scanner indent = new Scanner(new FileReader(f));
String ptu = "";
while(indent.hasNextLine()) {
currentLine = indent.nextLine();
currentLine = currentLine.trim();
char[] line = currentLine.toCharArray();
int i = 0;
while(i < line.length){ //Here I define the position of the Bracet for Indentation
if(line[i] == '('){

inBracket.addFirst(i);
}

i++;
}
if(!inBracket.isEmpty()){//here I indent with the position of the bracket and I remove the first(First In First Out)
if(!currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}

currentLine = space + currentLine;
inBracket.removeFirst();

}else if(currentLine.contains(")")){
int spaceadded = 0;
String space ="";
while(spaceadded <= inBracket.getFirst()){
spaceadded++; space += " ";
}

currentLine = space + currentLine;

inBracket.removeFirst();
}
}


ptu += currentLine +"\n";

}
indent.close() ;
System.out.println(ptu);
return ptu;




}

最佳答案

如果您期望自动缩进,您将不会得到这样的代码。您应该自己实现它,添加\n 空格(或\t)字符来格式化代码。 JEdi​​torPane 不理解您的代码逻辑。您(使用代码解析器)应该为您拥有的代码行定义父/子关系。

定义父/子的情况的一个例子是 XML。请参阅the XMLEditorKit节点缩进的位置。

关于java - Java Swing JeditorPane 中的自动缩进括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com