I want to have my JFileChooser use the system's LookAndFeel, but have the rest of my components use Nimbus. Since each platform provides a different FileChooserUI, how would I set the FileChooserUI property in UIManager to the system's LookAndFeel?
A component is created with the current LAF. So you can try something like:
Set LAF to the system LAF
Create the JFileChooser
Reset the LAF to Nimbus
Not sure is this will cause any problems with the file chooser or not.
If you are using windows you can use Windows file chooser :
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class FileSelection {
public static String getPath(){
String path =null;
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);
path=dialog.open();
shell.close();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
return path;
}
}
getPath() will returns the direct path to the selected file, but note that you must download org.eclips.swt package and add the .jar file to your class path.
You can download it here : Download
If you are not interesting of using this filechooser then Check this example.
Related
I've been browsing the site since yesterday and I can't see to find anything that answers my question, so I decided to just ask.
I'm making a pretty basic java GUI, it's designed to be run alongside files that wont be included in the actual java package for compatibility and easier customization of those files, I doubt they could be included either way as they have their own .jars and other things.
So, the problem I'm having is that the GUI application is in the main folder and I need it to locate and open txt files a couple sub-folders deep, in notepad without requiring a full file path as I'll be giving this project out to some people when it's done.
Currently I've been using this to open the files, but will only work for files in the main folder and trying to edit in any file paths did not work.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
Runtime rt=Runtime.getRuntime();
String file;
file = "READTHIS.txt";
try {
Process p=rt.exec("notepad " +file);
} catch (IOException ex) {
Logger.getLogger(NumberAdditionUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
if someone knows a way to do this, that'd be great.
On another note, I'd like to include the file shown above (READTHIS.txt) inside the actual java package, where would I put the file and how should I direct java towards it?
I've been away from java for a long time so I've forgotten pretty much anything, so simpler explanations are greatly appreciated.
Thanks to anyone reading this and any help would be awesome.
Update 2
So I added to the ConfigBox.java source code and made jButton1 open home\doc\READTHIS.txt in Notepad. I created an executable jar and the execution of the jar, via java -jar Racercraft.jar, is shown in the image below. Just take the example of what I did in ConfigBox.java and apply it to NumberAdditionUI.java for each of its JButtons, making sure to change the filePath variable to the corresponding file name that you would like to open.
Note: The contents of the JTextArea in the image below were changed during testing, my code below does not change the contents of the JTextArea.
Directory structure:
\home
Rasercraft.jar
\docs
READTHIS.txt
Code:
// imports and other code left out
public class ConfigBox extends javax.swing.JFrame {
// curDir will hold the absolute path to 'home\'
String curDir; // add this line
/**
* Creates new form ConfigBox
*/
public ConfigBox()
{
// this is where curDir gets set to the absolute path of 'home/'
curDir = new File("").getAbsolutePath(); // add this line
initComponents();
}
/*
* irrelevant code
*/
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
Runtime rt = Runtime.getRuntime();
// filePath is set to 'home\docs\READTHIS.txt'
String filePath = curDir + "\\docs\\READTHIS.txt"; // add this line
try {
Process p = rt.exec("notepad " + filePath); // add filePath
} catch (IOException ex) {
Logger.getLogger(NumberAdditionUI.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
/*
* irrelevant code
*/
Update
This is the quick and dirty approach, if you would like me to add a more elegant solution just let me know. Notice that the file names and their relative paths are hard-coded as an array of strings.
Image of the folder hierarchy:
Code:
Note - This will only work on Windows.
import java.io.File;
import java.io.IOException;
public class Driver {
public static void main(String[] args) {
final String[] FILE_NAMES = {"\\files\\READTHIS.txt",
"\\files\\sub-files\\Help.txt",
"\\files\\sub-files\\Config.txt"
};
Runtime rt = Runtime.getRuntime();
// get the absolute path of the directory
File cwd = new File(new File("").getAbsolutePath());
// iterate over the hard-coded file names opening each in notepad
for(String file : FILE_NAMES) {
try {
Process p = rt.exec("notepad " + cwd.getAbsolutePath() + file);
} catch (IOException ex) {
// Logger.getLogger(NumberAdditionUI.class.getName())
// .log(Level.SEVERE, null, ex);
}
}
}
}
Alternative Approach
You could use the javax.swing.JFileChooser class to open a dialog that allows the user to select the location of the file they would like to open in Notepad.
I just coded this quick example using the relevant pieces from your code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Driver extends JFrame implements ActionListener {
JFileChooser fileChooser; // the file chooser
JButton openButton; // button used to open the file chooser
File file; // used to get the absolute path of the file
public Driver() {
this.fileChooser = new JFileChooser();
this.openButton = new JButton("Open");
this.openButton.addActionListener(this);
// add openButton to the JFrame
this.add(openButton);
// pack and display the JFrame
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// handle open button action.
if (e.getSource() == openButton) {
int returnVal = fileChooser.showOpenDialog(Driver.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
// from your code
Runtime rt = Runtime.getRuntime();
try {
File file = fileChooser.getSelectedFile();
String fileAbsPath = file.getAbsolutePath();
Process p = rt.exec("notepad " + fileAbsPath);
} catch (IOException ex) {
// Logger.getLogger(NumberAdditionUI.class.getName())
// .log(Level.SEVERE, null, ex);
}
} else {
System.exit(1);
}
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Driver driver = new Driver();
}
});
}
}
I've also included a link to some helpful information about the FileChooser API, provided by Oracle: How to use File Choosers. If you need any help figuring out the code just let me know, via a comment, and I'll try my best to help.
As for including READTHIS.txt inside the actual java package, take a gander at these other StackOverflow questions:
Getting file from same package?
Reading a text file from a specific package?
How to include text files with executable jar?
Creating runnable jar with external files included?
Including a text file inside a jar file and reading it?
Suppose a font Kalpurush.ttf (you may find this font here). As it is an Assamese Font and may not have installed in everyone's computer, so, I've embedded this font in my website. It displays fine in any browser, (except android webview. I do not have any headache about android). In fact I've never found any Assamese font to be so nice.
Now I've tried this same font in a Java Swing Application. I've written this class:
public class AssameseFont {
public AssameseFont(){}
public Font Assamese(){
File file = new File("kalpurush.ttf");
Font as = null;
try{
FileInputStream input = new FileInputStream(file);
as = Font.createFont(Font.TRUETYPE_FONT, file);
as = as.deriveFont(Font.PLAIN, 18);
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(as);
}
catch(FontFormatException | IOException e){
JOptionPane.showMessageDialog(null, ""+e);
}
return as;
}
}
I use to call this in my components using setFont() method.
But some of my texts does not display as it should be.
Why does it happen? Is it a font problem? Or am I doing anything wrong in my java code?
As it is an Assamese Font and may not have installed in everyone's computer, so, I've embedded this font in my website. ..
File file = new File("kalpurush.ttf");
That file will point to a (non-existent) file on the user's machine.
The font must instead be accessed by URL.
See also Setting custom font.
The code seen on the linked thread, but with the kalpurush.ttf font.
import java.awt.*;
import javax.swing.*;
import java.net.URL;
class DisplayFont {
public static void main(String[] args) throws Exception {
URL fontUrl = new URL("http://assameseonline.com/css/kalpurush.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
font = font.deriveFont(Font.PLAIN,20);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
JLabel l = new JLabel(
"The quick brown fox jumps over the lazy dog. 0123456789");
l.setFont(font);
JOptionPane.showMessageDialog(null, l);
}
}
I just added a standard "Open file" dialog to a small desktop app I'm writing, based on the JFileChooser entry of the Swing Tutorial. It's generating a window that looks like this:
but I would prefer to have a window that looks like this:
In other words, I want my file chooser to have Windows Vista/Windows 7's style, not Windows XP's. Is this possible in Swing? If so, how is it done? (For the purposes of this question, assume that the code will be running exclusively on Windows 7 computers.)
It does not appear this is supported in Swing in Java 6.
Currently, the simplest way I can find to open this dialog is through SWT, not Swing. SWT's FileDialog (javadoc) brings up this dialog. The following is a modification of SWT's FileDialog snippet to use an open instead of save dialog. I know this isn't exactly what you're looking for, but you could isolate this to a utility class and add swt.jar to your classpath for this functionality.
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 ();
}
}
Even native Windows applications can get this type of dialog displayed on Windows 7. This is usually controlled by flags in OPENFILENAME structure and its size passed in a call to WinAPI function GetOpenFileName. Swing (Java) uses hooks to get events from the Open File dialog; these events are passed differently between Windows XP and Windows 7 version.
So the answer is you can't control the look of FileChooser from Swing. However, when Java gets support for this new look, you'll get the new style automatically.
Another option is to use SWT, as suggested in this answer. Alternatively you can use JNA to call Windows API or write a native method to do this.
Java 8 may finally bring a solution to this, but unfortunately (for Swing apps) it comes only as the JavaFX class FileChooser:
I've tested this code from here and it indeed pops a modern dialog (Windows 7 here):
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
//Show open file dialog
File file = fileChooser.showOpenDialog(null);
To integrate this into a Swing app, you'll have to run it in the javafx thread via Platform.runLater (as seen here).
Please note that this will need you to initialize the javafx thread (in the example, this is done at the scene initialization, in new JFXPanel()).
To sum up, a ready to run solution in a swing app would look like this :
new JFXPanel(); // used for initializing javafx thread (ideally called once)
Platform.runLater(() -> {
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
//Show open file dialog
File file = fileChooser.showOpenDialog(null);
});
A bit of a hack, and slightly less empowered than the Swing version, but have you considered using a java.awt.FileDialog? It should not just look like the Windows file chooser, but actually be one.
I don't believe Swing would cover that though it may, if it doesn't you may need to look at something like SWT, which would make use of the actual native component, or do a custom UI element, like something out of the "Filthy Rich Clients" book.
good question +1 , looks like as they "forgot" to implements something for Win7 (defaultLookAndFeel) into Java6, but for WinXP works correclty, and I hope too, that there must exists some Method/Properties for that
anyway you can try that with this code,
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
class ChooserFilterTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
String[] properties = {"os.name", "java.version", "java.vm.version", "java.vendor"};
for (String property : properties) {
System.out.println(property + ": " + System.getProperty(property));
}
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
jfc.addChoosableFileFilter(new FileFilter() {
#Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".obj");
}
#Override
public String getDescription() {
return "Wavefront OBJ (*.obj)";
}
#Override
public String toString() {
return getDescription();
}
});
int result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
System.out.println("Displayed description (Metal): " + (result == JOptionPane.YES_OPTION));
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(jfc);
} catch (Exception e) {
e.printStackTrace();
}
jfc.showOpenDialog(null);
result = JOptionPane.showConfirmDialog(null, "Description was 'All Files'?");
System.out.println("Displayed description (System): " + (result == JOptionPane.YES_OPTION));
}
};
SwingUtilities.invokeLater(r);
}
private ChooserFilterTest() {
}
}
Couldn't make this work for directories though!! The DirectoryDialog throws us back to the tree style directory chooser which is the same as the one listed in the question. The problem is that it does not allow me to choose/select/open hidden folders. Nor does it allow for navigation to folders like AppData, ProgramData etc..
The Windows 7 style filedialog (swt) does allow navigation to these folders, but then again, does not allow for folder selection :(
Update
To view hidden folders use JFileChooser and have setFileHidingEnabled(false). The only mandate with this is that users need to have 'show hidden files, folders and drives' selected in the
Folder Options -> View
of Windows Explorer
You won't get the flexibility of an address bar, but if you were looking around for a non-tree like file chooser in Java, which also lets you browse/view Hidden files/folder - then this should suffice
John McCarthy's answer seems to be the best. Here some suggestions.
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.Image;
Add image on top left corner. It's important that you use "getResourceAsStream", you'll notice after export as Runnable jar:
Display display = new Display();
Shell shell = new Shell(display);
InputStream inputImage = getClass().getResourceAsStream("/app/launcher.png");
if (inputImage != null) {
shell.setImage(new Image(display, inputImage));
}
User's home directory:
String filterPath = System.getProperty("user.home");
Get absolut pathname instead of filter-dependent pathname, which is wrong on other drive.
String absolutePath = dialog.open();
Since Swing emulates various L&F's, I guess your best bet would be to upgrade your JRE to the very latest and hope that the JFileChooser UI has been updated.
JFileChooser has always been a bit odd looking with Swing, also a bit slow.
Try using SWT's filechooser or you could wrap the C calls in JNA.
Im Trying to load my images on to Java but when running the code nothing appears inside my JFrame.
The way im doing it is calling my Image function from my main:
import java.awt.*; // Graphics stuff from the AWT library, here: Image
import java.io.File; // File I/O functionality (for loading an image)
import javax.swing.ImageIcon; // All images are used as "icons"
public class GameImage
{
public static Image loadImage(String imagePathName) {
// All images are loades as "icons"
ImageIcon i = null;
// Try to load the image
File f = new File(imagePathName);
if(f.exists()) { // Success. Assign the image to the "icon"
i = new ImageIcon(imagePathName);
}
else { // Oops! Something is wrong.
System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");
System.exit(0);
}
// Done. Either return the image or "null"
return i.getImage();
} // End of loadImages method
}
And then calling it here:
GI_Background = GameImage.loadImage("Images//background.jpg");
GI_DuskyDolphin = GameImage.loadImage("Images//DuskyDolphin.jpg");
If this is not enough information I'll gladly supply the rest of the code :)
Thanks
If the image is part of the application, do not use a File but use the java resource mechanism.
URL imageUrl = getClass().getResource("/Images/background.jpg");
return new ImageIcon(imageURL).getImage();
The resource URL will return null when not found.
If the application is packed in a .jar, you can open that with 7zip/WinZip or so, and check the path. It must be case-sensitive, and using / (not backslash).
I'm not quite sure what you try to achieve...
to load an image with a method, this will be enough:
private Image loadImage(String fileName){
return (new ImageIcon(fileName)).getImage();
}
Afterwards, i would create a JLabel with the Image as background;
ImageIcon image = getImage( filename );
JLabel imageLabel = new JLabel( image );
imageLabel.setSize( image.getIconHeight, image.getIconWidth );
JFrame frame = new JFrame();
frame.add( imageLabel );
Try this and feel free to aks again if i does not work for you, or thats not want you want :)
I have made a button, but I don't now how to make it open a specific directory like %appdata% when the button is clicked on.
Here is the code ->
//---- button4 ----
button4.setText("Texture Packs");
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser=new JFileChooser("%appdata%");
int status = fileChooser.showOpenDialog(this);
fileChooser.setMultiSelectionEnabled(false);
if(status == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
// do something on the selected file.
}
}
And I want to make something like this ->
private void button4MouseClicked(MouseEvent e) throws IOException {
open folder %appdata%
// Open the folder in the file explorer not in Java.
// When I click on the button, the folder is viewed with the file explorer on the screen
}
import java.awt.Desktop;
import java.io.File;
public class OpenAppData {
public static void main(String[] args) throws Exception {
// Horribly platform specific.
String appData = System.getenv("APPDATA");
File appDataDir = new File(appData);
// Get a sub-directory named 'texture'
File textureDir = new File(appDataDir, "texture");
Desktop.getDesktop().open(textureDir);
}
}
Execute a command using Runtime.exec(..). However, not every OS has the same file explorer, so you need to handle the OS.
Windows: Explorer /select, file
Mac: open -R file
Linux: xdg-open file
I wrote a FileExplorer class for the purpose of revealing files in the native file explorer, but you'll need to edit it to detect operating system.
http://textu.be/6
NOTE: This is if you wish to reveal individual files. To reveal directories, Desktop#open(File) is far simpler, as posted by Andrew Thompson.
If you are using Windows Vista and higher, System.getenv("APPDATA"); will return you C:\Users\(username}\AppData\Roaming, so you should go one time up, and use this path for filechooser,
Just a simple modified Andrew's example,
String appData = System.getenv("APPDATA");
File appDataDir = new File(appData); // TODO: this path should be changed!
JFileChooser fileChooser = new JFileChooser(appData);
fileChooser.showOpenDialog(new JFrame());
More about windows xp, and windows vista/7/8