1
votes

I am new to ANTLR4, when I was first trying it out in command line I was using the grun with gui parameter. Now I am developing a Java application and I want to display the same dialog while executing my Java program.

I generated the ParseTree successfully, and I can navigate through it. But I want to display it as well. I think it has something to do with TreeViewer class but I couldn't figure out how to use it.

Thanks

2

2 Answers

2
votes

TreeViewer is a Swing Component so you should be able to add it to any other SwingComponent, e.g a JPanel.

To instantiate a TreeViewer(List<String> rules, Tree tree) you will have to provide:

  • a complete list of rule names, you can use null here, but using the result of Parser.getRuleNames() produces a better result
  • a tree, which is the result of your parsing (something like XXXContext).
1
votes

copied from another post

import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.gui.TreeViewer;

/**
 * A simple demo to show AST GUI with ANTLR
 * @see http://www.antlr.org/api/Java/org/antlr/v4/runtime/tree/gui/TreeViewer.html
 * 
 * @author wangdq
 * 2014-5-24
 *
 */
public class HelloTestDrive {
    public static void main(String[] args) {
        //prepare token stream
        CharStream stream = new ANTLRInputStream("hello antlr");
        HelloLexer lexer  = new HelloLexer(stream);   
        TokenStream tokenStream = new CommonTokenStream(lexer);
        HelloParser parser = new HelloParser(tokenStream);
        ParseTree tree = parser.r(); 

        //show AST in console
        System.out.println(tree.toStringTree(parser));

        //show AST in GUI
        JFrame frame = new JFrame("Antlr AST");
        JPanel panel = new JPanel();
        TreeViewer viewr = new TreeViewer(Arrays.asList(
                parser.getRuleNames()),tree);
        viewr.setScale(1.5);//scale a little
        panel.add(viewr);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,200);
        frame.setVisible(true);
    }
}