Specifying the input - java

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 ?

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.

java value recieved from client-server program used in another program

My project looks like: I have a bike speedometer attached to simple bike and connected to Raspberry Pi, which is connected over ethernet cable to laptop.
What I want to do is: Raspberry measure the speed of bike wheel and send this value over ethernet cable to laptop. Laptop now uses recieved value and speed up a video, which is played in VLC.
I have working java program on RPi to measure speed of a wheel, I have a working client (on laptop)-server (on RPi) java program to send values from RPi to laptop, and I have a working java program to control speed of video playing in VLC on laptop.
But my problem is, that I don't know how to use values, recieved from RPi over client-server program, in my program, which control speed of video, playing in VLC.
Down are my codes for client and to control speed of video.
Client code:
package player;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static int inputPlayer = 0;
public static void main(String[] args) throws UnknownHostException, IOException {
String accept;
int input;
DataInputStream inC = null;
Scanner sc1 = null;
Socket s = null;
try {
s = new Socket ("169.254.218.194", 1342);
Scanner sc = new Scanner (System.in);
System.out.println("Accept connection!");
accept = sc.next();
PrintStream p = new PrintStream (s.getOutputStream());
p.println(accept);
//inC = new DataInputStream(s.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
while (true) {
sc1 = new Scanner (s.getInputStream());
input = sc1.nextInt();
if (input > 0) {
inputPlayer = input;
}
System.out.println("I" + input);
//System.out.println("IP" + inputPlayer);
}
}
public int getInputPlayer () {
return this.inputPlayer;
}
}
Player code:
package player;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
public class Player {
private final JFrame frame;
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
public static void main(final String[] args) {
new NativeDiscovery().discover();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Player(args);
}
});
}
public Player(String[] args) {
frame = new JFrame("My First Media Player");
frame.setBounds(100, 100, 600, 400);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
Scanner in = new Scanner (System.in);
frame.setContentPane(contentPane);
frame.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia("file:URL");
mediaPlayerComponent.getMediaPlayer().skip(1000);
client c = new client();
float i = c.getInputPlayer();
while (true) {
//float i = in.nextFloat();
//System.out.println(i);
mediaPlayerComponent.getMediaPlayer().setRate(i);
}
}
}
Everything I want to do is to use variable inputPlayer from client class as variable i in Player class.
As I have done, Eclipse return me error: "[000000001ade9eb0] core input error: input control fifo overflow, trashing type=2"
Thanks for your help.
Jan
There are several problems here:
the code in the client class (btw, class names should begin with uppercase) is never run. You've put all the code in that class in a main method, which only gets executed if you run the application by choosing that class. Essentially, you have two separate applications here. Even if you were to run them at the same time, it wouldn't help you since one would not have direct access to instances of classes in the other.
i is set only once and never updated inside the loop
you could turn that main method of the client class into an ordinary method, but even then you can't have two while(true) loops run at the same time if they are on the same thread.
If handling thread is a bit much for you at this stage, you could try simply combining both classes in one. One loop would scan for incoming data and set the players speed as it came. This might or might not work, depending on how the player itself is implemented, but you could give it a try.

Drawing parse tree in ANTLR4 using 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);
}
}

Add subtitle and basic operation panel in VLCJ # Java

Good day colleagues!
I had several trouble using VLCJ and other Java media API-s.
1) I'd add a simple *.srt file to my EmbeddedMediaPlayerCompononent, bot how is this possible?
2) Also, how can I configurate the VLC lib in an x64 Windows OS?
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files (x86)\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(),libVlc.class);
This not works well.
3) How could I add basic operation interface to my EmbeddedMediaPlayerCompononent like pause/play button?
Thank you, best regards! :)
My "VideoPlayer" class
package GUI.MediaPlayer;
import java.awt.BorderLayout;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import StreamBean.UIBean;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class VideoPlayer extends JFrame{
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
public VideoPlayer(String videoURL) {
String os = System.getProperty("os.name").toLowerCase();
if(os.startsWith("win")){
String registrytype = System.getProperty("sun.arch.data.model");
System.out.println("a rendszered : " +os+" - " +registrytype+ " bites");
if(registrytype.contains("32")){
//Windows 32 bites verzió
System.out.println("Belépett a 32-be");
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}else if(registrytype.contains("64")){
//Windows 64 bites verzió
System.out.println("Belépett a 64-be");
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files (x86)\\VideoLAN\\VLC");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}else{
JOptionPane.showMessageDialog(null, "Kérem előbb telepítse a VLC lejátszót.");
}
}
if(os.startsWith("mac")){
//Mac OSX kiadáshoz
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "/Applications/VLC.app/Contents/MacOS/lib/");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}
this.setTitle("Aktuális videó");
this.setLayout(new BorderLayout());
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
this.add(mediaPlayerComponent,BorderLayout.CENTER);
this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
//set the Jframe - this - resolution to the screen resoltuion
new UIBean().setWindowSize(this);
this.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia(videoURL);
}
}
To set an external subtitle file:
mediaPlayerComponent.getMediaPlayer().setSubTitleFile("whatever.srt");
How you add a pause/play button is entirely up to you, it requires standard Swing code that is not particular to vlcj. You add buttons to your user interface, and link those buttons up with the media player by using event listeners. For example, this is one way:
JButton playButton = new JButton("Play/Pause");
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
mediaPlayerComponent.getMediaPlayer.pause();
}
});
There are numerous reasons why the native library might not be found, but NativeLibrary.addSearchPath(...) certainly does work. You have to be sure you match the CPU architectures of your JVM and your VLC installation (32-bit JVM requires 32-bit VLC, 64-bit JVM requires 64-bit VLC). In most cases you should just use:
new NativeDiscovery().discover();
There are a whole bunch of step-by-step tutorials at http://capricasoftware.co.uk/#/projects/vlcj/tutorial
Focusing on the "basic operation interface" aspect of your question, note that EmbeddedMediaPlayerComponent extends Panel, an AWT component. Accordingly, the VLCJ overlay example shown here overrides paint(). This related, stand-alone example illustrates hit testing in such context.

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

Categories

Resources