I have a piece of code
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
public class Characters {
public static void main (String [] args) throws AWTException, InterruptedException {
TimeUnit.SECONDS.sleep(3);
Robot newRobot = new Robot();
StringSelection stringSelection;
Clipboard clipboard;
String text;
for (int i = 1; i <= 2; i++) {
TimeUnit.MILLISECONDS.sleep(1000);
text = String.valueOf(i);
stringSelection = new StringSelection(text);
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
if(i % 2 == 1) {
TimeUnit.MILLISECONDS.sleep(100);
newRobot.mouseMove(1141, 852);
newRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
newRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} else {
TimeUnit.MILLISECONDS.sleep(100);
newRobot.mouseMove(444, 859);
newRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
newRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
TimeUnit.MILLISECONDS.sleep(900);
newRobot.keyPress(KeyEvent.VK_CONTROL);
newRobot.keyPress(KeyEvent.VK_V);
newRobot.keyRelease(KeyEvent.VK_V);
newRobot.keyRelease(KeyEvent.VK_CONTROL);
newRobot.keyPress(KeyEvent.VK_ENTER);
}
}
}
On my Windows PC, if I changed applications, it would run the clicks and keys on said application, I have an original 3 second sleep to change applications. On my Mac, when the mouseMove part starts, it automatically changes the application back to Netbeans when I don't want that. Any setting to change that?
Related
I’ve been trying to make a program that will display a visual metronome that will flash in sync with a MIDI file by sensing a “click” track that I have added using a MIDI editor.
I only have a basic knowledge of Java programming but have been hacking my way through this project. In particular, I’m having problems with the graphical portion. As part of my testing and troubleshooting, I have added a println in a conditional statement that is true when the “click” starts, and this part seems to work well.
The clicks occur about 2 times per second, and each click lasts for about 1/10 of a second. I would like a rectangle shape that is red during the time the click is present, and gray when the click is not present. The attached code actually sorta works (a total hack job I’m sure) , but is one beat off (there is 72 clicks on the MIDI file I’ve been working with, but the JFrame only flashes 71 times).
I suspect the proper way would be to draw a rectangle and somehow change, or update, the fill color in the conditional statements. I’ve spent much time researching this and trying different approaches, but I really have no idea what would be the proper way to proceed.
I would greatly appreciate any guidance and maybe some code snippets.
import java.io.File;
import java.io.IOException;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Transmitter;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Midi6 extends JPanel implements Receiver
{
private static final int NOTE_ON = 144;
private static final int NOTE_OFF = 128;
int count = 0;
int count2 = 0;
Sequencer sequencer = MidiSystem.getSequencer();
String str = new String();
public Midi6() throws MidiUnavailableException, InvalidMidiDataException, IOException, InterruptedException
{
Sequence sequence = MidiSystem.getSequence(new File("miditest2.mid"));
sequencer.open();
sequencer.setSequence(sequence);
Transmitter transmitter = sequencer.getTransmitter();
transmitter.setReceiver(this);
sequencer.start();
}
public static void main(String[] args) throws InvalidMidiDataException, IOException, MidiUnavailableException, InterruptedException
{
Midi6 midi6 = new Midi6();
JFrame frame1=new JFrame();
frame1.add(midi6);
frame1.setSize(600,100);
frame1.getContentPane().setBackground( Color.LIGHT_GRAY);
frame1.setVisible(true);
}
synchronized public void send(MidiMessage message, long timeStamp)
{
if(message instanceof ShortMessage)
{
ShortMessage sm = (ShortMessage) message;
int channel = sm.getChannel();
if (sm.getCommand() == NOTE_ON)
{
if (channel == 0)
{
setBackground(Color.RED);
count ++;
System.out.println(count);
}
}
else if (sm.getCommand() == NOTE_OFF)
{
if (channel == 0)
{
setBackground(Color.LIGHT_GRAY);
}
}
else
{
}
}
}
#Override
public void close()
{
// TODO Auto-generated method stub
}
}
My friend and I have been working on a Java project to create a simple media player using the Media, MediaPlayer, and MediaView classes. However, from the start we've had issues successfully opening the video that we're using as a test file. After many angry runtime exceptions, we finally figured out that the source of our problem was the String being passed into each object (Media needs a String that represents the File Path in a URI format). After some modifications, we found that the following URI worked on my computer to open the File:
Media m = new Media("file:///C:/Users/mewww/Google%20Drive/Java/SmartPlay/EXO-MonsterMV.mp4");
MediaPlayer mp = new MediaPlayer(m);
MediaView mv = new MediaView(mp);
However, we later tried to implement an Open method that would allow the user to choose which File (as a File object) they wanted to play. When we did this, we used the following to open the file:
File currentFile = new File(null);
FileChooser fc = new FileChooser();
fc.setTitle("Open");
currentFile = fc.showOpenDialog(null);
Media m = new Media(currentFile.toURI().toString());
MediaPlayer mp = new MediaPlayer(m);
MediaView mv = new MediaView(mp);
This started giving us runtime exceptions again and so we used a println into the console to find out what the problem was. The string being used was now two "/"s short of what it was supposed to be as:
"file:/C:/Users/mewww/Google%20Drive/Java/SmartPlay/EXO-MonsterMV.mp4"
However, even after modifying the string, we still received the same runtime error as soon as the file was selected:
Exception in Application start method
java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
We then commented the whole Open method out and went back to our original code, but continue to receive the same errors.
Our full code is available here:
SmartPlay class
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import java.io.File;
import javafx.stage.FileChooser;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.application.Platform;
public class SmartPlay extends Application {
File currentFile;
Scene scene;
#Override
public void start(Stage primary) {
primary.setTitle("SmartPlay");
selectCurrentFileToOpen();
//Player(currentFile.toURI().toString().substring(0,5)+"//"+currentFile.toURI().toString().substring(5));
Player player = new Player("file:///C:/Users/mewww/Google%20Drive/Java/SmartPlay/EXOMonsterMV.mp4");
scene = new Scene(player, 720, 480, Color.BLACK);
player.setTop(makeMenus());
primary.setScene(scene);
primary.show();
}
private MenuBar makeMenus() {
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem openItem = new MenuItem("Open...");
openItem.setOnAction(e -> {
selectCurrentFileToOpen();
scene.setRoot(new Player(currentFile.toURI()));
});
MenuItem quitItem = new MenuItem("Quit");
quitItem.setOnAction(e -> Platform.exit());
fileMenu.getItems().addAll(openItem, quitItem);
return mb;
}
public boolean selectCurrentFileToOpen() {
FileChooser fc = new FileChooser();
fc.setTitle("Open");
currentFile = fc.showOpenDialog(null);
return true;
}
public void stop() {
}
public static void main(String[] args) {
launch(args);
}
}
Player class
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import java.net.URI;
public class Player extends BorderPane {
Media m;
MediaPlayer mp;
MediaView mv;
Pane p;
MediaBar bar;
public Player(String file) {
m = new Media(file);
mp = new MediaPlayer(m);
mv = new MediaView(mp);
p = new Pane();
p.getChildren().addAll(mv);
setCenter(p);
bar = new MediaBar(mp);
setBottom(bar);
setStyle("-fx-background-color:#cccccc");
mp.play();
}
}
MediaBar class
import javafx.scene.layout.HBox;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.media.MediaPlayer;
import javafx.scene.layout.Priority;
import javafx.scene.control.Slider;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.util.Duration;
public class MediaBar extends HBox {
Slider time = new Slider();
Slider vol = new Slider();
Button playButton = new Button("Pause");
Button halfSpeed = new Button("0.5x");
Button normalSpeed = new Button("1.0x");
Button doubleSpeed = new Button("2.0x");
Label volume = new Label("Volume: ");
Label nowTime;
MediaPlayer player;
public MediaBar(MediaPlayer play) {
player = play;
setAlignment(Pos.CENTER);
setPadding(new Insets(5,10,5,10));
vol.setPrefWidth(70);
vol.setMinWidth(30);
vol.setValue(100);
nowTime = new Label(formatTime(player.getCurrentTime()) + "/" + formatTime(player.getTotalDuration()));
HBox.setHgrow(time, Priority.ALWAYS);
playButton.setPrefWidth(30);
getChildren().addAll(playButton,time,nowTime,volume,vol);
}
public static String formatTime(Duration duration) { //StackOverflow: Jon Skeet
long seconds = (long) duration.toSeconds();
long absSeconds = Math.abs(seconds);
String positive = String.format(
"%d:%02d:%02d",
//absSeconds / 3600,
(absSeconds % 3600) / 60,
absSeconds % 60);
return seconds < 0 ? "-" + positive : positive;
}
}
So I ran your code in command line and I was able to get a more specific debug error. So it seems like the time formatting you do in your MediaBar is causing the error. I don't know exactly what you are trying to do with that but the way you format the time is incorrect. If you comment it out as well as the other things you use to add the time formatting the URI path will be correct and your video should run fine. I know that for the formatting you are missing a '%02d'. As for what you are formatting I am not too sure so I cannot help you there.
I have created a media player method is javafx which is called upon startup (below is the media player). My problem is that this pauses whenever I interact with a scroll pane by dragging or by zooming the player pauses and does not start again. Why is this the case and how may I fix this(included full application if you would to try it).
Method(Live code)
private static void MusicPlayer() {
if(musicList.peek() == null)
{
return;
}
MediaPlayer mediaPlayer = new MediaPlayer(new Media(new File(musicList.poll()).toURI().toString()));
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.dispose();
MusicPlayer();
});
});
}
Minimal
package minimalist;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class Minimal extends Application{
private static Queue<String> musicList = new LinkedList<String>();
public static void main(String[] args) throws IOException {
List<String> result = Files.find(Paths.get(".\\music"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".mp3"))
.map(path -> path.toString())
.collect(Collectors.toList());
for(int a = 0; a < result.size(); a++)
{
musicList.add(result.get(a));
}
MusicPlayer();
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
ScrollPane scrollpane = new ScrollPane();
Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/7/70/Kusatma_Zonaro.jpg");
ImageView imageView = new ImageView(image);
scrollpane.setContent(imageView);
scrollpane.setPannable(true);
Scene scene = new Scene(new StackPane(scrollpane));
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
primaryStage.show();
}
private static void MusicPlayer() {
if(musicList.peek() == null)
{
return;
}
MediaPlayer mediaPlayer = new MediaPlayer(new Media(new File(musicList.poll()).toURI().toString()));
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.dispose();
MusicPlayer();
});
});
}
}
This all seems to behave in something of a fragile manner.
I would not recommend launching the media player from the main method. The documentation is a bit lacking on threading policy for MediaPlayer, but since you are launching a regular JavaFX application it would seem sensible to follow the usual rules and only call methods on it from the JavaFX Application Thread. On my system, I was unable to get any music playing the way you had it set up.
I also had sporadic issues getting it to start playing after changing that; I guessed that maybe I was leaving system resources tied up after exiting, so I modified the code to ensure the player was disposed when the application ended. After both those changes, it behaved as expected. At no point though did I have any issues associated with user input; my guess is that these are caused by launching the media player from the main thread instead of from the FX Application Thread, and are probably system-dependent.
Here's the code that worked fine for me. I also cleaned up some of the redundancy in your code (iterating through Paths to convert them to Strings which you then convert back to Files so you can convert to a string representation of a URL seems somewhat circuitous; you also create a completely unnecessary list in that process, etc) and renamed things so that it abides by proper naming conventations):
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.Queue;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class Minimal extends Application{
private Queue<Path> musicList = new LinkedList<>();
private MediaPlayer mediaPlayer ;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
// Everyone should have this album. Edit the path if your musical taste is poor.
Files.find(Paths.get(System.getProperty("user.home"),"Music/iTunes/iTunes Media/Music/Thievery Corporation/Saudade/"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".m4a"))
.forEach(musicList::add);
playMusic();
ScrollPane scrollpane = new ScrollPane();
Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/7/70/Kusatma_Zonaro.jpg");
ImageView imageView = new ImageView(image);
scrollpane.setContent(imageView);
scrollpane.setPannable(true);
Scene scene = new Scene(new StackPane(scrollpane));
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
primaryStage.show();
}
#Override
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.dispose();
}
}
private void playMusic() {
if(musicList.peek() == null)
{
return;
}
mediaPlayer = new MediaPlayer(new Media(musicList.poll().toUri().toString()));
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.dispose();
playMusic();
});
});
}
}
Actually, i have already ask this question in here. But, i'm making mistake. I haven't already get the solution.
First, at the question before, i can get Rectangle with
Rectangle rectangle = textArea.modelToView( textArea.getCaretPostion() );
I'm also get X and Y position.
I'm creating a editor that can add new Text Area each i press Enter key. XY position with code above always give same return in every Text Area. Look my code.
import java.awt.Container;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class forquestion extends JFrame {
Container textAreaBox;
LinkedList<JTextComponent> textArea;
int nameTA;
public forquestion() {
int nameTA = 0;
textArea = new LinkedList<>();
textAreaBox = Box.createVerticalBox();
textAreaBox.add(Box.createVerticalGlue());
addLine();
this.add(textAreaBox);
this.setVisible(true);
}
public static void main(String[] args) {
forquestion app = new forquestion();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void addLine () {
JTextComponent temp_ta = createTextComponent();
textArea.add(temp_ta);
textAreaBox.add(textArea.getLast());
textAreaBox.add(Box.createVerticalGlue());
}
protected JTextComponent createTextComponent() {
JTextArea ta = new JTextArea("test");
/*if (count%2==0)
ta.setForeground(Color.red);
else
ta.setForeground(Color.GREEN);*/
ta.setFont(new Font("Courier New",Font.PLAIN,16));
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setName(Integer.toString(nameTA));
nameTA+=1;
basicKey("ENTER", enter, ta);
ta.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent ev) {
try {
taMousePressed(ev);
} catch (BadLocationException ex) {
Logger.getLogger(forquestion.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
return ta;
}
public void basicKey(String s, Action a, JTextArea ta) {
ta.getInputMap().put(KeyStroke.getKeyStroke(s), s);
ta.getActionMap().put(s, a);
}
Action enter = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
addLine();
}
};
private void taMousePressed(java.awt.event.MouseEvent ev) throws BadLocationException {
int now_focus = Integer.parseInt(ev.getComponent().getName());
int _caret;
_caret = textArea.get(now_focus).getCaretPosition();
Rectangle rectangle = textArea.get(now_focus).modelToView(_caret);
double x = rectangle.getX();
//int xc = textArea.get(now_focus).getLocation().x;
double y = rectangle.getY();
//int yc = textArea.get(now_focus).getLocation().y;
//double h = rectangle.getHeight();
//double w = rectangle.getWidth();
System.out.println(x);
System.out.println(y);
//System.out.println(xc);
//System.out.println(yc);
//System.out.println(h);
//System.out.println(w);
System.out.println("");
}
}
My code will print XY position each time you press a Text Area. But, the display always same in every text area. (Try to make many Text Area and give some text) Btw, it just simple code. You need change the window frame size for update the new text area after you press enter key..hahaha.
So, my question is: How can i get the XY position of caret (text cursor) in any Text Area. I want to display JPopmenu there. :)
I hope this question clear for you. Thx before.
The Rectangle reported back is relative to the text area, where it's 0x0 position is the top, left corner of the component.
If you use something like...
popup.show(textArea.get(now_focus), rectangle.x, rectangle.y + rectangle.height);
Where popup is a JPopupMenu, it will make the required translations to the screen itself.
Now. Having said that. Personally, I would prefer to use the popup API support provided by Swing. This is going to mean needing to create a custom component that extends from JTextArea to achieve it...
public class MyPopupTextArea extends JTextArea {
/*...*/
public Point getPopupLocation(MouseEvent evt) {
Rectangle rectangle = textArea.get(now_focus).modelToView(_caret);
Point p = rectangle.getLoction();
p.y += rectangle.height;
return p;
}
}
Then, based on your needs, you can use setComponentPopup to provide a shared instance of the JPopupMenu or, if required, create a custom JPopupMenu for each instance of the custom editor and use setComponentPopup as you see fit...no messing about with mouse listeners ;)
while running the program to grab frames from web cam captured video i am getting facing problem of NullPointerException. i tried to change the settings of capture devices but ther is no option like
"vfw:Microsoft WDM Image Capture (Win32):0"
cant locate device in jmf.
.so is mentioned directly into the code refering to the materials.but not working!
i am using net beans for this and libraries of jmf also included in netbeans.
please help me fix this.my code:
package VideoSource;
/**
*
* #author sri
*/
import java.awt.Frame;
import javax.imageio.ImageIO;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.media.Buffer;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.CaptureDeviceInfo;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.media.*;
public class frames {
public static final String DEVICE ="vfw:Microsoft WDM Image Capture (Win32):0";
//protected Player player;
public static void main(String args[]) throws IOException, CannotRealizeException{
try{
CaptureDeviceInfo cdi = CaptureDeviceManager.getDevice(DEVICE);
Player player = Manager.createRealizedPlayer(cdi.getLocator());
player.start();
FrameGrabbingControl frameGrabber = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = frameGrabber.grabFrame();
//BufferedImage buf1 = frameGrabber.grabFrame();
// Convert frame to an buffered image so it can be processed and saved
Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf));
if(img!=null){
RenderedImage img1=(RenderedImage) img;
int i=0;
File outputfile = new File("d:/Project/frame"+(i++)+".jpg");
ImageIO.write(img1, "jpg", outputfile);
}
else
System.out.println("null from frame grabbing");
//return img;
}
catch(NoPlayerException n)
{
}
}
}
i have exception as:
Exception in thread "main" java.lang.NullPointerException
at VideoSource.frames.main(frames.java:37)
Java Result: 1