Drawing parse tree in ANTLR4 using Java - java

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

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).

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);
}
}

Related

VLCJ-Pro Java returned: -57005

My task is to play multiple videos with a linked time scrubber in a grid, and I've gotten it to work (WITH VLCJ NOT VLCJ-PRO), but it is VERY finicky.
So I decided to give VLCJ-Pro a try, but I'm getting an error on the first line.
22:25:25.614 [main] INFO u.c.c.vlcj.discovery.NativeDiscovery - Discovery
found libvlc at 'D:\VLC'
C:\Users\trans\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: -57005
BUILD FAILED (total time: 0 seconds)
VLCJ-Pro is supposed to help with VLCJ's multi-video problems (native library crashes happen alot). So I figured I'd see if it helped with stability, but I can't even get it to run.
VLCJ-Pro Download Location
Here is my entire code I'm using to test the library. I'm using Netbeans as my IDE and I've added ALL the JAR libraries in the example code.
If you have any experience with VLCJ-Pro I would greatly appreciate any feedback on how I'm going wrong.
package vlcjprodemo;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
import uk.co.caprica.vlcj.version.LibVlcVersion;
import uk.co.caprica.vlcjpro.client.player.OutOfProcessMediaPlayer;
import uk.co.caprica.vlcjpro.client.player.OutOfProcessMediaPlayerComponent;
import uk.co.caprica.vlcjpro.client.player.OutOfProcessMediaPlayerComponentFactory;
public class VLCJProDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new NativeDiscovery().discover();
LibVlcVersion.getVersion();
//CRASHES HERE
OutOfProcessMediaPlayerComponentFactory theFactory = new OutOfProcessMediaPlayerComponentFactory();
OutOfProcessMediaPlayerComponent theComponent = theFactory.newOutOfProcessMediaPlayerComponent();
Canvas theVideoCanvas = new Canvas();
theVideoCanvas.setFocusable(true);
theVideoCanvas.setSize(new Dimension(1920, 1080));
theVideoCanvas.setLocation(0, 0);
theComponent.setVideoSurface(theVideoCanvas);
OutOfProcessMediaPlayer theMediaPlayer = theComponent.mediaPlayer();
theMediaPlayer.setRepeat(true);
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.setBackground(Color.black);
mainFrame.setMaximumSize(new Dimension(1920, 1080));
mainFrame.setPreferredSize(new Dimension(1920, 1080));
mainFrame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrame.add(theVideoCanvas);
mainFrame.pack();
mainFrame.setVisible(true);
theMediaPlayer.playMedia("horse.avi");
}
}
Probably you are trying to use a trial/demo version of vlcj-pro that has expired.
If so, you need to wait until a new trial version is published.

Swing component add to ScrollPane(JavaFX)

I'm making JavaFX application which will open pdf files. I found free library for PDF Viewer but it's made in Swing. So I need to add JPanel to ScrollPane(JavaFX). I tried but without success.
I got this error:
Aug 13, 2016 9:59:09 PM org.icepdf.core.pobjects.Document
WARNING: PDF write support was not found on the class path.
I found here on stackoverflow how to add swing component to javafx pane and I do that but I got this error.
Any suggestion is welcome.
package application;
import java.awt.Component;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
import javafx.embed.swing.SwingNode;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
public class PDFView{
public JPanel viewerComponentPanel;
public static Node showPDF(File sFiles) throws MalformedURLException {
String filePath = sFiles.toURI().toURL().toString();
// build a controller
SwingController controller = new SwingController();
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
final SwingNode swingNode = new SwingNode();
createAndSetSwingContent(swingNode, viewerComponentPanel);
// Open a PDF document to view
controller.openDocument(filePath);
return swingNode;
}
private static void createAndSetSwingContent(final SwingNode swingNode, JPanel viewerComponentPanel) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
swingNode.setContent(viewerComponentPanel);
}
});
}
}
This is main class where I call the method from PDFView class
for(int i=0;i<fileNumber;i++){
choosedName=sFiles[i].getName();
String ext=choosedName.substring(choosedName.lastIndexOf(".") + 1);
switch (ext) {
case "doc":
break;
case "docx":
break;
case "pdf":
tab = new Tab();
tab.setText(choosedName);
s1=new ScrollPane();
tab.setContent(s1);
s1.setContent(PDFView.showPDF(sFiles[i]));
tpane.getTabs().add(tab);
I downloaded icepdf viewer and core jars.
and a minimal change in your code:
//String filePath = sFiles.toURI().toURL().toString();
String filePath = sFiles.getAbsolutePath();
then, it worked for me, hope also works for you...

How to specify the base classifier in stacking method when using Weka API?

I was trying to use stacking method weka api in java and found a tutorial for single classifier. I tried implementing stacking using the method described in the tutorial method but the classification is done with default Zero classifier in Weka.I was able to set meta classifier using "setMetaClassifier" but not able to change the base classifier.What is the proper method to set base classifier in stacking ?
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.meta.Stacking;
import weka.core.Instances;
public class startweka {
public static void main(String[] args) throws Exception{
BufferedReader breader=new BufferedReader(new FileReader("C:/newtrain.arff"));
Instances train=new Instances(breader);
train.setClassIndex(train.numAttributes()-1);
breader.close();
String[] stackoptions = new String[1];
{
stackoptions[0] = "-w weka.classifiers.functions.SMO";
}
Stacking nb=new Stacking();
J48 j48=new J48();
SMO jj=new SMO();
nb.setMetaClassifier(j48);
nb.buildClassifier(train);
Evaluation eval=new Evaluation(train);
eval.crossValidateModel(nb, train, 10, new Random(1));
System.out.println(eval.toSummaryString("results",true));
}}
Ok i found the answer in other forum weka nabble.The code for setting base classifier is
Stacking nb=new Stacking();
SMO smo=new SMO();
Classifier[] stackoptions = new Classifier[1];
stackoptions[0] = smo;
nb.setClassifiers(stackoptions);
OR
Stacking nb=new Stacking();
SMO smo=new SMO();
Classifier[] stackoptions = new Classifier[] {smo};
nb.setClassifiers(stackoptions);

Java Formatter append method within anon ActionListener

Sorry in advance if this has been answered elsewhere, i am probably just searching the wrong tags.
I wish to create a log file, of various variables, with the use of an anonymous inner class implementing ActionListener. This will be attached to a JButton.
Using the Formatter, gives me exactly what i require in a line, but i want to keep
all previous logs of this event (I dont care if its before or after the last entry).
After various methods of me hitting a wall I found through some surfing of this site and others you can possibly do this with an append method in a constructor with Formatter.
Is it possible to use append while in an inner class with Formatter?
If not can you suggest another Java writer that will still meet my needs?
I'm still a beginner so the less complicated the better...for now.
If it's possible within the inner class and with formatter without any additional
imports/packages, please give us a hint or a link and i will keep searching.
I have attached a small compilable sample code, that may help if anyone is interested in
having a play.
thanks,
weekendwarrior84
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Formatter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestProgram extends JFrame{
private FlowLayout lay;
public TestProgram(){
super("Sample Program");
lay = new FlowLayout();
setLayout(lay);
final JLabel label1 = new JLabel("Label One");
add(label1);
final TextField field1 = new TextField(8);
add(field1);
final JLabel label2 = new JLabel("Exception Label");
add(label2);
final JButton button1 = new JButton
("Log Data");
add(button1);
button1.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
if(button1.isSelected());
try{
Formatter fm = new Formatter("C:\\Test\\testlog.txt");
fm.format("%s%s%s%s", "Sample Value: ",label1.getText(),
" Sample Value2: ",field1.getText());
fm.close();
}
catch(Exception ee){
label2.setText("Make Sure Path exists, C:\\Test\\testlog.txt");
}
}
}
);
}
}
Main
import javax.swing.JFrame;
public class TestMain{
public static void main (String[] args){
TestProgram ts = new TestProgram();
ts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ts.setSize(1200,500);
ts.setVisible(true);
}
}
Is there a specific reason why you want to do this with Formatter? It reads like you want to do some very basic logging, for which there are numerous implementations in Java to do the dirty work for you. Even the java.util.logging package would suffice to append log-lines to a file upon button-click. I'd personally suggest logback, but that's just a preference.
If you do insist on doing the file operations yourself this question's answers might be for you. The formatting can just be done with the MessageFormat-class before writing the complete line to the file.
As Promised, it is still a WIP but it solved my current problem. It was mainly confusion on what was possible with the writers, and the belief i required the formatter.
if(button1.isSelected());
String path = "C:\\Test\\testlog.txt";
String mylog = "\r\n"+"Sample Value: " + label1.getText()+" Sample Value2: "+field1.getText();
File file = new File(path);
FileWriter writer;
try {
writer = new FileWriter(file,true);
BufferedWriter buffer = new BufferedWriter(writer);
writer.append(mylog);
buffer.close();
}catch (IOException e1) {
label2.setText("Make Sure Path exists, C:\\Test\\testlog.txt");

Specifying the input

Is there any way to force a user to give his/her input via overwriting certain characters.
i.e.:
First screen:
Amount: ___.__
Second:
Amount: 1__.__
... goes like this ...
Finally:
Amount: 1200.50
But i want to be sure that numbers will be printed as soon as user presses the keyboard.
Thanks in advance.
p.s.: OS is MS Windows 9x/XP/Vista/7. And the application is for console.
MaskFormatter mf1 = new MaskFormatter("#####.##");
mf1.setPlaceholderCharacter('_');
JFormattedTextField ftf1 = new JFormattedTextField(mf1);
Here's the full code
import java.awt.Container;
import java.text.ParseException;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.MaskFormatter;
public class Test {
public static void main(String args[]) throws ParseException {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
MaskFormatter mf1 = new MaskFormatter("######.###");
mf1.setPlaceholderCharacter('_');
JFormattedTextField ftf1 = new JFormattedTextField(mf1);
content.add(ftf1);
f.setSize(300, 100);
f.setVisible(true);
}
}
You don't say what OS you're on. For performing advanced input terminal work, this could be important.
You could spend some time implementing such a solution in Java by capturing keystrokes yourself, regenerating the input line etc. On the other hand, have you looked at JLine ?

Categories

Resources