I've been making a program that uses a JFileChooser. I've set the application up with
UIManager.getSystemLookAndFeelClassName()
Which works just fine for pretty much everything under Ubuntu. The only problem I've run into so far is that the JFileChooser comes out looking pretty awful:
Is there a way to make this look like the default file chooser in Ubuntu? ie.
I've tried using
UIManager.getCrossPlatformLookAndFeelClassName()
Which makes the JFileChooser dialog look better, but still not native looking, and it ruins the rest off the application's feel too.
Thanks.
If I recall correctly, the stock JDK used gtk1, but ubuntu uses gtk2 currently. I forget where but i've come across gtk2 for java somewhere. Google? Probably not what you were hoping for, sorry.
You might see if FileDialog is any more appealing; here's an example.
The Nimbus look and feel has a decent file chooser. Although this will affect your entire application, you might like the look.
Also you can build your own file chooser if needed.
You can also use SWT instead of swing.
Does Swing support Windows 7-style file choosers?
The following code is from above link
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class SWTFileOpenSnippet {
public static void main (String [] args) {
Display display = new Display ();
Shell shell = new Shell (display);
// Don't show the shell.
//shell.open ();
FileDialog dialog = new FileDialog (shell, SWT.OPEN | SWT.MULTI);
String [] filterNames = new String [] {"All Files (*)"};
String [] filterExtensions = new String [] {"*"};
String filterPath = "c:\\";
dialog.setFilterNames (filterNames);
dialog.setFilterExtensions (filterExtensions);
dialog.setFilterPath (filterPath);
dialog.open();
System.out.println ("Selected files: ");
String[] selectedFileNames = dialog.getFileNames();
for(String fileName : selectedFileNames) {
System.out.println(" " + fileName);
}
shell.close();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}
Related
I am a beginner in Java, so my question would be pretty basic. Here is my problem I have a class where I process folders for query matching and indexing.I have made a GUI for the same where I will ask the user to select the directory from JFileChooser.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser f=new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showOpenDialog(null);
if(f.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
}
System.out.println(f.getSelectedFile().getAbsolutePath());
}
Now I want to give this directory path to my other class so it can process the folder
obj = new object();
boolean index = false;
String str = "";
InputStreamReader r = new InputStreamReader(System.in);
obj.dataDirectory = // here should be the path of the selected folder
For Example, if a user selects c:\Desktop\TextFiles then what I want want is obj.dataDirectory=c:\Desktop\TextFiles
I tried creating an object of GUI class in this class and then tried calling that method in this class but I don`t know how to do it exactly or even if it is possible.
Thanks in Advance
I'm using rundll32 url.dll,FileProtocolHandler my_file.dotx to open files under Windows.
It works fine with .docx documents, but when I try it with .dotx documents (template documents), it creates a new .docx based on the template.
Just as the normal behavior in the windows explorer : when you double-click on a .dotx template file, it creates a new .docx file based on it. If you want to open the real .dotx file, you have to right-click on it and select "open" instead of "new".
Question is: how to do the same with rundll32? Is there an option in the command to force the opening of the underlying template instead of creating a new document?
Edit: I need a way to do it without C functions, just plain text, in the command line (I'm using Java to do it).
Maybe you can wrap a simple C program around ShellExecute, passing the verb OPEN.
ShellExecute(NULL, TEXT("open"),
TEXT("rundll32.exe"), TEXT("url.dll,FileProtocolHandler pathToGadget"),
NULL, SW_SHOWNORMAL);
I found this example here.
edit:
Since you're doing this in Java - you could try a JNI wrapping of the ShellExceute function like this (from the example I found on The Wannabe Java Rockstar and butchered)
public static boolean execute(String file, String parameters) {
Function shellExecute =
Shell32.getInstance().getFunction(SHELL_EXECUTE.toString());
Int32 ret = new Int32();
shellExecute.invoke(ret, // return value
new Parameter[] {
new Handle(), // hWnd
new Str("open"), // lpOperation
new Str(file), // lpFile
new Str(parameters), // lpParameters
new Str(), // lpDirectory
new Int32(1) // nShowCmd
});
if(ret.getValue() <= 32) {
System.err.println("could not execute ShellExecute: " +
file + ". Return: " + ret.getValue());
}
return (ret.getValue() > 32);
}
public static void main(String[] args) {
ShellExecute.execute("rundll32.exe","url.dll,FileProtocolHandler pathToGadget" );
}
Using java, I would like some code that could get me the paths for:
1) Start Menu for Current User
2) Start Menu for All User
I need the answer for both WinXP and Win7. So hopefully there is a general answer that can get me both.
You have no other choice but to write a DLL and call native Windows API:
SHGetFolderPath(NULL, CSIDL_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, &szPathBuffer)
SHGetFolderPath(NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, &szPathBuffer)
If you really need the root of Start menu, use CSIDL_STARTMENU and CSIDL_COMMON_STARTMENU.
The full list of known folders: CSIDL.
If you target Windows Vista and above, use SHGetKnownFolderPath function instead of SHGetFolderPath.
You can use JNA library to call native Windows API without writing native code yourself but pure Java code.
Okay, I figured out a solution, but maybe someone else has a more eligant one.
I plan on doing something like "Runtime.getRuntime().exec(command);" and the command will be a "reg query" to query the following registry keys:
Current User can referenced by: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Start Menu
All users can be referenced by: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Common Start Menu
These are the same for both Win7 and WinXP. If anyone else knows of a better solution, I'll be happy to look at it too.
In my program I used a simple System.getProperty("user.home") + "/Start Menu/Programs" This gave me the user's Start Menu folder.
It worked on windows 7 and windows 10. I tried this because in order to get a user's desktop, all I had to do was call System.getProperty("user.home") + "/Desktop". SO I figured that it might work for the Start Menu as well, and seemed to have worked fine. I can delete and write files to the Start Menu just like I can with the desktop. Whether this is the right way to do something like this or not, I have no idea. But I'm just sharing what worked for me.
Another option is managing Start Menu items from vbs API.
I made a Java Wrapper for that.
// Install Start Menu
WindowsUtils.installStartMenuItem(WindowsUtils.SPECIALFOLDER_Programs,"my_start_menu", "explorer.exe", "http://www.google.es","Acceso directo a google");
// Uninstall Start Menu
WindowsUtils.uninstallStartMenuItem(WindowsUtils.SPECIALFOLDER_Programs, "my_start_menu");
i recently found this
public class VBSUtils {
public static String SF_ALLUSERSDESKTOP = "AllUsersDesktop";
public static String SF_ALLUSERSSTARTMENU = "AllUsersStartMenu";
public static String SF_ALLUSERSPROGRAMS = "AllUsersPrograms";
public static String SF_ALLUSERSSTARTUP = "AllUsersStartup";
public static String SF_DESKTOP = "Desktop";
public static String SF_FAVORITES = "Favorites";
public static String SF_MYDOCUMENT = "MyDocuments";
public static String SF_PROGRAMS = "Programs";
public static String SF_RECENT = "Recent";
public static String SF_SENDTO = "SendTo";
public static String SF_STARTMENU = "StartMenu";
private VBSUtils() { }
public static String getSpecialFolder(String folder) {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n"
+ "wscript.echo WshShell.SpecialFolders(\"" + folder + "\")\n"
+ "Set WSHShell = Nothing\n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
result = input.readLine();
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result;
}
public static void main(String[] args){
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_ALLUSERSSTARTMENU));
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_ALLUSERSDESKTOP));
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_DESKTOP));
System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_PROGRAMS));
//System.out.println(VBSUtils.getSpecialFolder(VBSUtils.SF_STARTUP));
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to add hyperlink in JLabel
In my program, I am searching through an index using Lucene and I am retrieving files. I have created XML files for the retrieved docs from the Lucene's search. Now, I want to make these XML files as hyperlinks and display to the user as the search results. That is I want the XML files to be open when the user clicks on this hyperlink. Any help appreciated!?
for(int i=0;i<file_count;i++)
{
file=str+index[i]+".xml";
JLabel label = new JLabel(file,JLabel.CENTER );
label.setOpaque(true);
label.setBackground(Color.RED);
panel.add(label) ;
label.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() > 0)
{
Runtime r= Runtime.getRuntime();
try {
System.out.println("testing : Inside mouseclicked");
Process p = r.exec("cmd.exe /c start "+file);
System.out.println("opened the file");
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.out.println();
}
}
}
});
}
Here is the code that I have made. In this, I am suppose to get output on the screen "file_count" no of times. I am getting that but what is happening is all the links are showing the same file when clicked. Help?
If I do understand your question correctly, you want to allow the user to open a file. The Desktop class (available as of JDK1.6) allows this
File fileToOpen = ...;
Desktop desktop = Desktop.getDesktop();
desktop.open( fileToOpen )
Depending on how you want to present this to the user, you can opt for your JLabel code with the listener but it is probably easier to use a JButton with an ActionListener. Both approaches are discussed in detail in the answer Marko Topolnik already suggested in his comment. The only difference is that they wanted to open an URL, while you want to open a file (so that answer uses the browse method instead of the open method of the Desktop class).
I would like to write an application who creates input for a non-Java application in Windows. With the Robot class it's easy to generate the input, but I need to set the focus to another application's text box and enter the text over there.
Don't worry I'm not trying to write something malicious, I just want to use Java to "extend" an old application written in Delphi.
CMDOW is a command line utility which allows you to perform various window actions such as activating/deactivating, listing, minimising/maximising etc.
Alternatively, you can write a VBScript to activate another application. For example:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate("Firefox")
Then use Runtime.exec from your Java app to execute the script.
This will help you activate another application.
However, it will be much more difficult if you want to focus on a textbox within the other application and write some text.
Detecting a special application and bringing that one to the front might require a native helper, but for the moment you could send ALT+TAB to activate the "next" application
This works:
public void switchFocus() {
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_TAB);
} catch(AWTException e) {
// handle
}
}
you just need to implement a convenience method to map chars (from a String) to key event values... (or find some existing solution)
Configure a delay otherwise it won't work:
Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.delay(10); //set the delay
r.keyRelease(KeyEvent.VK_ALT);
r.keyRelease(KeyEvent.VK_TAB);
On Mac, there is possible to do it with AppleScript. AppleScript is integrated to system, so it will be always functional.
https://developer.apple.com/library/content/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html
You need only detect you are on mac and has name of the application.
Runtime runtime = Runtime.getRuntime();
String[] args = { "osascript", "-e", "tell app \"Chrome\" to activate" };
Process process = runtime.exec(args);
You need to add enough delay for the application to fully initialize and gain focus.
Here's a basic working example... Andreas_D is correct that you need to emulate the system key to switch between programs... (Alt+Tab on Windows, Cmd+Tab on OS X)
import java.awt.*;
import static java.awt.event.KeyEvent.*;
import java.io.IOException;
public class RobotSample {
//https://stackoverflow.com/questions/4782231
private static Integer[] KEY_CODES = { VK_S, VK_T, VK_A, VK_C, VK_K, VK_O, VK_V, VK_E, VK_R, VK_F, VK_L,VK_O, VK_W, VK_DECIMAL, VK_C, VK_O, VK_M, VK_SLASH, VK_Q, VK_U, VK_E, VK_S, VK_T, VK_I, VK_O, VK_N, VK_S, VK_SLASH, VK_4, VK_7, VK_8, VK_2, VK_2, VK_3, VK_1, VK_ENTER };
public static void main( String[] args ) throws IOException {
try {
Robot robot = new Robot();
Runtime runtime = Runtime.getRuntime();
runtime.exec( "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" );
robot.keyPress( VK_ALT );
robot.keyPress( VK_TAB );
robot.keyRelease( VK_ALT );
robot.keyRelease( VK_TAB );
//Chill a sec...
robot.delay( 1000 );
for(int i = 0; i < KEY_CODES.length; ++i) {
robot.keyPress( KEY_CODES[i] );
robot.keyRelease( KEY_CODES[i] );
robot.delay( 80 );
}
} catch( AWTException e ) {
e.getMessage();
}
}
}