I'm using ImageJ a lot to look at image stacks composed of a number of single images sitting in one folder. I can just drag and drop the respective folder into the ImageJ GUI and it creates a scrollable visualization, which is very convenient. It could be even more convenient though since each time I do it, a dialog appears asking whether I want to open all images in the folder as a stack. Is it possible to make it default to "Yes"? Would I need to change the source code and compile it myself..? If that is the case, where could I start looking?
A suggestion would be to make a feature request to the author of Imagej Wayne rasband, e.g., at the Github repository:
https://github.com/imagej/imagej1
Or you can write a small macro (use the macro recorder with the menu actions!) which can be also be installed in ImageJ. Something like:
run("Image Sequence...", "open=C:\\images\\ sort");
Here the macro docs:
https://imagej.nih.gov/ij/developer/macro/macros.html
https://imagej.nih.gov/ij/docs/guide/146-14.html
To disable the dialog in the source code: Find the source file ij>plugin>DragAndDrop.java. From its openDirectory method, delete the dialog-related lines and assign boolean values to convertToRGB and virtualStack, both of which are normally defined by check boxes in the now defunct dialog window. The code should now look like this:
private void openDirectory(File f, String path) {
if (path==null) return;
if (!(path.endsWith(File.separator)||path.endsWith("/")))
path += File.separator;
String[] names = f.list();
names = (new FolderOpener()).trimFileList(names);
if (names==null)
return;
convertToRGB = false;
virtualStack = false;
String options = " sort";
if (convertToRGB) options += " convert_to_rgb";
if (virtualStack) options += " use";
IJ.run("Image Sequence...", "open=[" + path + "]"+options);
DirectoryChooser.setDefaultDirectory(path);
IJ.register(DragAndDrop.class);
}
I did this with ImageJ 1.51p. The source code can be downloaded here. After making these changes, just run the build.xml ant script.
Note that writing a macro might provide a cleaner and more portable way to achieve this--refer to Marcel's answer for further reading.
Related
Problem:
I wanted to create a directory such that when I click on a button for one time the directory must be created with the name "Node_1". when I click on the same button once again the directory must be created with the name "Node_2".
Please do not bother about the button. I need the code where the count must be incremented as stated above.
The below sample code will create a directory with the name "Node_1" When I click once.
But when I click button Once again, it will create a directory with the same name "Node_1" again. But I wanted to create with the name "Node_2".
String src = "C:\\Users\\DELL\\Documents\\NetBeansProjects\\src\\Nodes\\Node_1\\n1_sample.txt";
Hope, this will help:
int clickCounter = 0;
void onClick() {
++clickCounter;
.
.
String src = "...\\Node_" + clickCounter + "\\...txt"
}
Note: Learn to ask question in a better way. Share what you want to achieve, what you've tried already, and what problem you are facing, and also keep it simple.
I'm working on an Eclipse RCP project and need to let the user select some file.
For convenience, based on some conditions, the initial directory of the file choosing dialog should be set prior to opening it.
As I'm bound to Eclipse RCP / SWT, I am working with the org.eclipse.swt.widgets.FileDialog.
The documentation of this FileDialog points out to use the setFilterPath(String string)-method which should do exactly what I need (see documentation).
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.html"});
dialog.setFilterPath("c:\\temp");
String result = dialog.open();
Unfortunately it is not working, at least not "every time".
I have currently no installation to check on it, but I'm quite sure that the feature would work totally fine on a Windows 200/XP/Vista machine.
I am working with a Windows 7 machine and I think I am suffering from the behaviour described here for lpstrInitialDir.
At least, this is exactly the behaviour I am facing: The path is good the first time I open the dialog, but the second time, the path is initially set to the last chosen path.
This seems to be convenient in most cases, but it is not in mine.
Can this be right?
If so, have I any chance on changing the behaviour according to my needs?
Thanks for any helping answer!
I ran into the same problem on Windows 10 and found a solution that seems to be working for me. A code snippet from the DirectoryDialog led to the right direction:
if (filterPath != null && filterPath.length() > 0) {
String path = filterPath.replace('/', '\\');
char[] buffer = new char[path.length() + 1];
path.getChars(0, path.length(), buffer, 0);
if (COM.SHCreateItemFromParsingName(buffer, 0, COM.IID_IShellItem, ppv) == OS.S_OK) {
IShellItem psi = new IShellItem(ppv[0]);
/*
* SetDefaultDirectory does not work if the dialog has
* persisted recently used folder. The fix is to clear the
* persisted data.
*/
fileDialog.ClearClientData();
fileDialog.SetDefaultFolder(psi);
psi.Release();
}
}
The FileDialog misses this statement 'fileDialog.ClearClientData()'. My solution is to execute the following code before setting the path and open the dialog:
long [] ppv = new long [1];
if (COM.CoCreateInstance(COM.CLSID_FileOpenDialog, 0, COM.CLSCTX_INPROC_SERVER, COM.IID_IFileOpenDialog, ppv) == OS.S_OK) {
IFileDialog fileDialog = new IFileDialog(ppv[0]);
fileDialog.ClearClientData();
fileDialog.Release();
}
Now you can set the filterpath without Windows messing things up.
I found a simple Solution for the Problem you described (I had the exact same Problem).
Just rearrange the your code like this:
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterPath("c:\\temp"); // This line is switched with the following line
dialog.setFilterExtensions(new String [] {"*.html"});
String result = dialog.open();
Somehow the Order of the methods called is relevant.
Are you using the same FileDialog object when you re-open it?
I ran a few quick tests and found that, if you re-set the filterPath, the dialog opens in the correct location.
If I open the same object again, it starts in the previously selected location.
I want to build a tread safe JAVA application which:
Play *.mp4 or other format HD media files (full-screen mode 1920x1080)
Add event bindings to applet (I'll be using touchscreen monitor)
I tried to search a lot, but found only outdated examples of JMF (VLCJ and etc.).
So I want you to ask from where to start building this applet.
What libraries I can include.
I found a similar project here: Media Shuffle
But I want my media files to be located in one folder and they appear in applications as icons which start selected video (VLC fullscreen or other cross-platform media player) to play on 1st touch. The second touch have to stop player and go to the main page.
Please, share your ideas how I can do that. Any code examples would be great.
I would recommend vlcj because i am sure it has all the formats you could need or have.Its not outdated at all and easy to start with.If you want to display a video graphically i dont think you could ever find so simple instructions like you mention but if you organize all steps that i will mention and explain in more depth you will see that vlcj is the best option for handling media like that (as it goes in my opinion).I also like and recommend JavaFx because of the effects you can make with that but its too difficult for me to setup and code in that stuff.
So, lets begin.Firstly, i would like to say that i have implemented the vlcj in a Swing-based application (in Windows) but that should not make you sad because for an immediate popup player that you mention we could just make a jdialog and place the video-surface in its contentPane.
Steps
1)So the first thing that should be done is to download vlc media player (we will need the 32 bit version that plays in both 32bit or 64bit computer environments).I had a terrible month trying to configure why my app wasnt loading the required libraries succesfully and found out that when you run a jar exetutable file it runs on 32-bit jvm(in eclipse was running in 64bit jvm and everything was ok.Thats why we need 32bit version), while i had 64-bit native libraries to load from.Anyways if you download and install 32bit vlc media player make somewhere a folder to include your project(lets say "C:/MyProject") inside MyProject create another folder and call it for instance "Needed"(here we will place all the required libraries for vlcj in order to work properly).Now from the contents of C:\Program Files (x86)\VideoLAN\VLC copy the plugins directory and the 4 dlls
(axvlc.dll,libvlc.dll,libvlccore.dll,npvlc.dll) and paste them inside your Needed folder
2)Now if you work in Eclipse IDE or similar you will need to make a folder in your project (lets say "lib") and inside that create another folder( name it "jars" ).In jars folder place the following jars: jna-3.5.1.jar, platform-3.5.1.jar,vlcj-2.2.0.jar.You can find these jars from vlcj google project.And then just include them to your classpath(either select them and right-click->add to build path or go to project properties->Java build path and add those 3 jars).Thats all for setup before we begin any coding with player setup.
3) You have to load now vlcj before starting using it.I just use this code to make that possible(i will explain it shortly dont worry).
public void LoadLibrary(){
SwingWorker loadWorker;
loadWorker = new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
// TODO Auto-generated method stub
Thread.sleep(2000);
path = new File("").getAbsolutePath().toString();
path = path.replace(".", "");
path = path.replace("\\", "//");
path = path+"//Needed";
if(RuntimeUtil.isWindows()){
NativeLibrary.addSearchPath(
"libvlc",path
);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
}
else if(RuntimeUtil.isNix()){
NativeLibrary.addSearchPath(
"libvlc",path
);
}
mediaPlayerFactory = new MediaPlayerFactory();
player = mediaPlayerFactory.newEmbeddedMediaPlayer();
CanvasVideoSurface videoSurface = mediaPlayerFactory.newVideoSurface(canvas);
player.setVideoSurface(videoSurface);
return null;
}
};
loadWorker.execute();
}
So what i do is to make a thread for Swing-based apps because you cannot play media if your media canvas is not displayable and everything in the constructor is fully built when its code is done.That means that before making the player we should first create a delay(mine is 2 seconds) for our constructor to end his job and our JFrame(or jWindow or jDialog etc) to become displayable.Next i calculate my path dynamically taking the path of my runnable jar(attention: not from workspace inside Eclipse) and entering the Needed folder to implement the required native libraries.Inside the if statement i tell the system to look for the libvlc.dll in the specific path i calculated and then load it and thus make one step forward to play media files.Outside if-else statement i actually create my player and place the canvas for its VideoSurface(canvas is a Canvas java.awt Object I use WindowsCanvas because i work only in windows, you could find for linux or mac a similar canvas(dont worry about that!)) Outside the Swing-Worker field(the thread) i just telling the thread to be executed (important as a call-function instruction).
4)To play a file i just use a button somewhere in my app to call an action event each time it is pressed so that we do something inside it.I for example make a JFileChooser to choose a media file from.You can easily search for it but here is my code:
final JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter0 = new FileNameExtensionFilter(".wav", "wav");
FileNameExtensionFilter filter1 = new FileNameExtensionFilter(".mp3","mp3");
FileNameExtensionFilter filter2 = new FileNameExtensionFilter(".mpg","mpg");
FileNameExtensionFilter filter3 = new FileNameExtensionFilter(".mp4","mp4");
FileNameExtensionFilter filter4 = new FileNameExtensionFilter(".avi","avi");
FileNameExtensionFilter filter5 = new FileNameExtensionFilter(".flv","flv");
FileNameExtensionFilter filter6 = new FileNameExtensionFilter(".wmv","wmv");
FileNameExtensionFilter filter7 = new FileNameExtensionFilter(".3gp", "3gp");
FileNameExtensionFilter filter8 = new FileNameExtensionFilter(".swf", "swf");
FileNameExtensionFilter filter9 = new FileNameExtensionFilter(".mkv", "mkv");
FileNameExtensionFilter filter10 = new FileNameExtensionFilter(".flac", "flac");
FileNameExtensionFilter filter11 = new FileNameExtensionFilter("Music & Videos","wav","mp3","mpg","mp4","avi","flv","wmv","3gp","swf","mkv","flac","VOB");
FileNameExtensionFilter filter12 = new FileNameExtensionFilter("Music","wav","mp3","flac");
FileNameExtensionFilter filter13 = new FileNameExtensionFilter(".VOB", "VOB");
FileNameExtensionFilter filter14 = new FileNameExtensionFilter("Videos","mpg","mp4","avi","flv","wmv","3gp","swf","mkv","VOB");
chooser.setFileFilter(filter14);
chooser.setFileFilter(filter2);
chooser.setFileFilter(filter3);
chooser.setFileFilter(filter4);
chooser.setFileFilter(filter5);
chooser.setFileFilter(filter6);
chooser.setFileFilter(filter13);
chooser.setFileFilter(filter7);
chooser.setFileFilter(filter8);
chooser.setFileFilter(filter9);
chooser.setFileFilter(filter12);
chooser.setFileFilter(filter0);
chooser.setFileFilter(filter1);
chooser.setFileFilter(filter10);
chooser.setFileFilter(filter11);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
File myfile1 = chooser.getSelectedFile();
myfilepath1 = chooser.getSelectedFile().getAbsolutePath();
}
player.startMedia("file:///"+myfilepath1);
player.pause();
Those file filters are some of the media file types that vlcj can play for u.What i do is opening a file dialog to choose a file from and if i choose a file i hold its path(usefull for saying vlcj where to look for it).
5)Now to play the file u just have to type the following code :
player.play();
Maybe inside another action event of another Button.
6) if you finish writing those all you have to do is to export your project to a runnable jar file into your MyProject folder first created and run it (attention by double-clicking it (not from console(else it will be runned with 64bit jvm and you dont want that cause you have 32 bit natives and vlcj dont accept those conflicts)))
In Conclusion,i have to say that these steps worked for me.I hope they will help you go further in your app developement.
Regards,
PeGiannOS
First you have to
// create a player to play the media specified in the URL
Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
Now
mediaPlayer.start(); // start playing the media clip
I hope it work!
VLCJ isn't outdated, it's actively developed and immensely flexible and powerful in what it can achieve. I'm using it in my application to display a number of video streams inside the application at once, as well as doing things such as text overlays simultaneously. It's sometimes tricky to do this, but definitely possible.
There are a number of basic (up-to-date) examples to get you started with VLCJ here.
From within Java, I am opening an Excel file with the default file handler (MS Excel, in this case :-) ) using the method described in this stackoverflow question:
Desktop dt = Desktop.getDesktop();
dt.open(new File(filename));
However, the Excel program doesn't get the focus. Is there any easy way to do so?
Edit: There is a related stackoverflow question for C#, but I didn't find any similar Java method.
Edit 2: I've did some simple tests, and discovered that Excel starts and gets the focus whenever no instance of Excel is running. When Excel is already open en NOT minimized, the application doesn't get the focus. If instead the Excel Windows was minimized, the above code will trigger a maximization of the window and Excel getting the focus (or vice versa :-) ).
If you only care about Windows (implied in the question), you can change the way you invoke Excel: use "cmd start...".
I have been using this piece of code to launch Windows applications for some time now. Works every time. It relies on the file association in Windows to find the application. The launched application becomes the focused window on the desktop.
In your case, Excel should be associated with .xls, .csv and other typical extensions. If it is, Windows will launch Excel, passing your file to it.
Usage:
MyUtilClass.startApplication( "c:\\mydir\\myfile.csv", "my window title" );
file is the full path to the input file for Excel and title is the window title (the application may or may not take it - Excel changes the window title).
public static void startApplication( String file, String title )
{
try
{
Runtime.getRuntime().exec( new String[] { "cmd", "/c", "start", title, file } );
}
catch( Exception e )
{
System.out.println( e.getMessage() );
}
}
From a scala-program, which runs in the JVM too, I can open an application, and that get's the focus by default. (Tested with xUbuntu, which is a kind of Linux).
import java.awt.Desktop
val dt = Desktop.getDesktop ();
dt.open (new java.io.File ("euler166.svg"));
I can't say, whether this is specific for Linux, or maybe something else - however starting Inkscape in my example, excel in yours, may take a few seconds, while the user impatiently clicks in the javaprogram again, thereby claiming the cursor back. Did you check for that?
You could then change to the last application, at least on Linux and Windows with ALT-Tab aka Meta-Tab (again shown in scala code, which you can easily transform to javacode, I'm sure):
import java.awt.Robot
import java.awt.event._
val rob = new Robot ()
rob.keyPress (KeyEvent.VK_META)
rob.keyPress (KeyEvent.VK_TAB)
rob.keyRelease (KeyEvent.VK_TAB)
rob.keyRelease (KeyEvent.VK_META)
but unfortunately the unknown source off more trouble, also known as user, might do nothing, so switching would be the false thing to do. Maybe with a thread, which checks for a certain amount of time, whether the java-program has the focus, but it keeps a form of roulette, in an interactional environment, because the user may have a fast or slow machine, or change to a third application meanwhile, and so on. Maybe a hint before triggering the new app is the best you can do?
I have a JDialog with a button/textfield for the user to select a file. Here's the code:
FileDialog chooser = new FileDialog(this, "Save As", FileDialog.SAVE );
String startDir = saveAsField.getText().substring( 0, saveAsField.getText().lastIndexOf('\\') );
chooser.setDirectory(startDir);
chooser.setVisible(true);
String fileName = chooser.getFile();
My problem is that instead of seeing an All Files filter, I want to provide a custom filter, e.g. for Word docs or something. I setup a custom FilenameFilter using setFilenameFilter(), but it didn't seem to work. I did notice that it says in the docs that the custom filter doesn't work in Windows (this runs in Windows XP/Vista/7). Here was my implementation of the filter:
chooser.setFilenameFilter( new geFilter() );
public class geFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return name.endsWith( ".doc" ) || name.endsWith( ".docx" );
}
}
Am I doing something wrong here? Also, I want a description to appear in the box, like "Microsoft Word (*.doc *.docx)" but I'm not sure how to do that.
Any and all help is appreciated.
AWT isn't really the preferred way of writing Java GUI apps these days. Sun seems to have mostly abandoned it. The two most popular options are Swing and SWT. So I think they didn't really develop the APIs very extensively to add modern features. (err, to answer your question: No you don't appear to be able to do that with AWT)
Swing has the advantage that it is truly write-once-run-anywhere and it can look exactly the same everywhere. There are Look & Feels that try to make Swing look native, some are better than others (Mac isn't terrible, Windows is okay, GTK isn't). Still, if you want an app that really looks and acts EXACTLY the same everywhere, Swing will let you do that. Plus it runs out-of-the-box without any extra libraries. Performance isn't great.
Swing's JFileChooser will let you do what you want. Create a subclass of FileFilter and call setFileFilter on the JFileChooser.
SWT takes the write-once-run-anywhere to the opposite extreme. You still have one codebase that you write against, but it actually uses the native widgets on each platform so it generally looks like a native app (not perfect everywhere, but still impressive). It's fast and pretty reliable in my experience. Eclipse (and other high profile software) uses SWT so it's in pretty heavy use. But it does require platform-specific JARs and DLLs.
since you are using JDialog, that is a swing class why not using JFileChooser?
JFileChooser fc = new JFileChooser("C:\\");
fc.setFileFilter(new FileNameExtensionFilter("Microsoft Word (*.doc, *.docx)", "doc", "docx"));
FileNameExtensionFilter is a nice Java 6 class that does exactly what you want.
I am also trying to do that. I want to use FileDialog instead of JFileChooser.
I found the answer here: http://www.rgagnon.com/javadetails/java-0247.html
He says that "on the Win platform, the setFilenameFilter method don't work. We must use the setFile method instead to set a filter."
There is source code at the specified link.
I tested and it works:
FileDialog fd = new FileDialog((Frame) null, "Save File", FileDialog.SAVE);
fd.setFile("*.txt");
fd.setVisible(true);
String file = fd.getFile();
System.out.println(file);
System.exit(0);
If you ever use JavaFX 2, the FileChooser class will do exactly what you need without any of JFileChooser/FileDialog problems. You can also embed JavaFX 2 components inside Swing applications, but you need JavaFX runtime.
Example:
FileChooser fc = new FileChooser();
FileChooser.ExtensionFilter filter;
filter = new FileChooser.ExtensionFilter("Text files (*.txt)", "*.txt");
fc.getExtensionFilters().add(filter);
File f = fc.showOpenDialog(primaryStage);
System.out.println(f);
You can call the native Windows Filedialog (CFileDialog) with JNI. Filters can be set for CFileDialog easily.
I wrote a simple wrapper class for CFileDialog several months ago, If you are interested, you can get the source and binary from
Xfiledialog project on google code
Just use setFilenameFilter method of the FileDialog instance fd:
fd.setFilenameFilter(new FilenameFilter()
{
#Override
public boolean accept(File file, String s)
{
// enter code to return TRUE or FALSE here
return s.contains(".txt");
}
});