I have the following Java 8 Swing code:
JButton button = new JButton("Browse");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose file as input");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Filter", "xls", "xlsx");
fileChooser.setFileFilter(filter);
if (fileChooser.showOpenDialog(mainWindow) == JFileChooser.APPROVE_OPTION) {
File selection = fileChooser.getSelectedFile();
createFile(selection);
}
}
});
The idea is that the user selects a directory and then types the name of a new file that the app will then create. But when I click the button this is what I see:
Notice how there's no "File Name" text field where you can enter the new file name? What configurations do I need to change in order to get this?
You're using the showOpenDialog which, as the name suggests, shows a "Open File" dialog to select a file to open. It usually doesn't make sense to allow a non-existent file to be opened.
If you want to allow the user to select a new file, you probably want the showSaveDialog which shows a "Save File" dialog and (should) allow a new file to be created.
Related
In Java I want to load a file [whatever format it is] in its own format using JFileChooser. Means I don't want to read and display the contents inside my JFrame. Instead I want them to open/load like an image open in a Windows Photo Viewer/Irfan Viewer and a PDF open in Adobe Reader By clicking a Button.
I had searched a lot. But all tutorial I read tells how to print a line "opening this file/You are selected this file" by clicking a JButton. Nobody is actually opening/loading a file on a button click. May be I am not getting correctly what they said because I am new to Java. I hope my problem is clear and please help...
Here is the code that I got from a tutorial page:
public class JFileChooserTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComboBox Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
Here is what I want to do with Java. here is an example with windows:
A Browse Button Click opens this window
And when I select the XLS file and click OPEN button, an XLS file will open. I want to do the exact same with Java. Hope it is more clear now.
You may try using Desktop.open():
Desktop.getDesktop().open(selectedFile);
EDIT
You need to update here:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
java.awt.Desktop.getDesktop().open(selectedFile);//<-- here
}
}
});
Sample code from site:
If I understand you correctly, you want to select a file and pass it to the system's default application. Unfortunately, this is highly dependable on your operating system. For Windows you can pass that to the command line like this:
String systemcall = "cmd /C start \"\" \"" + absolutePath + "\"";
Runtime runTime = Runtime.getRuntime();
HomeLogger.instance().info("EXECUTE " + systemcall);
runTime.exec(systemcall);
The String absolute Path must be the exact locatin of the file, e.g. "C:\test.txt". I hope that helps!
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
add(menubar,BorderLayout.NORTH);
menubar.add(file);
JMenuItem Open = new JMenuItem("OPEN... Ctrl+O");
file.add(Open);
Open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Frame f = new Frame();
FileDialog openf = new FileDialog(f, "Open");
openf.setVisible(true);
}
});
Well, I tried to use a lot many examples on the internet which makes the open button work as you can see i have already made the design but i need help in how to open a .txt file on clicking the open button in the filedialog. how am i supposed to do that?? i would really appreciate if anyone can help me out with few lines of code that actually works as i am sick of searching error generating codes from the internet.
The documentation states:
The FileDialog class displays a dialog window from which the user can
select a file.
Since it is a modal dialog, when the application calls its show method
to display the dialog, it blocks the rest of the application until the
user has chosen a file.
Therefore, instead of calling .setVisible(true) you can call .show() on the dialog, and then you can use getFile() to get the file that was chosen, or getFiles() if you are using multipleMode.
To read the file you can use:
public static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
yourComponent.setText(readFile(openf.getFile(), Charset.defaultCharset()));
(Taken from this question)
I'm trying make a JFileChooser for selecting a folder. In this FileChooser, I'd like users to have the option of creating a new folder, and then selecting that. I've noticed that JFileChooser "Save" dialogs have a "new folder" button by default, but no similar button appears in "open" dialogs. Does anyone know how to add a "new folder" button to an "Open" dialog?
Specificially, I'd like to add the button to a dialog created using this code:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
#Override
public boolean accept(File f) {
return f.isDirectory();
}
#Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.OPEN_DIALOG);
frame.getContentPane().add(fc);
frame.pack();
frame.setVisible(true);
Ok. In the end I solved this by using a "save" dialog instead of an "open" dialog. The standard save dialog already has a "new folder" button, but it also has a "Save as:" panel at the top, which I didn't want. My solution was to use a standard save dialog, but to hide the "Save as" panel.
Here's the code for the save dialog:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
#Override
public boolean accept(File f) {
return f.isDirectory();
}
#Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.SAVE_DIALOG);
fc.setApproveButtonText("Select");
frame.getContentPane().add(fc);
frame.setVisible(true);
This part locates and hides the "Save as:" panel:
ArrayList<JPanel> jpanels = new ArrayList<JPanel>();
for(Component c : fc.getComponents()){
if( c instanceof JPanel ){
jpanels.add((JPanel)c);
}
}
jpanels.get(0).getComponent(0).setVisible(false);
frame.pack();
End result:
EDIT
There's one quirk with this solution, which comes up if the user presses the approve button while there's no directory currently selected. In this case the directory returned by the chooser will correspond to whatever directory the user was viewing, concatenated with the text in the (hidden) "save as:" panel. The resulting directory may be one that doesn't exist. I handled this with the code below.
File dir = fc.getSelectedFile();
if(!dir.exists()){
dir = dir.getParentFile();
}
I am trying to put a JFileChooser box on my GUI but if I just do this
JFileChooser filechooser = new JFileChooser ();
then it will just show a huge file selection window on the panel (I do not want that), so I want to make a small box filechooser (with a name for example "choose file") that when I click it, a window will popup, so then I can choose the file.
Use a button to open your file chooser and use setPreferredSize() method to make the file chooser smaller in size:
JButton button = new JButton("Choose a file!");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle( "Choose a file" );
fileChooser.setVisible( true );
fileChooser.setPreferredSize( new Dimension(100, 100) );
}
});
Call
filechooser.setPreferredSize (new java.awt.Dimension (800, 800));
before calling showOpenDialog with whatever Dimension you like.
But I would suggest to either maximize the Dialog, because in the moment I like to open a File, I don't like to watch something else - find a file, and close the dialog, without much scrolling, because somebody thought it looks more nice.
If you like to prevent wasting space, you can precalculate the needed size for the window, which might be a lot of work, but could pay off, if you use the Component frequently.
So here is te thing, Im trying to do an Applet for a webgame to produces "custom" avatars, this avatar are for a kind off an army of a country, so the avatar cosnsit on the image of the choice of the user, and a frame on the picture thtat represent the quad that the user belongs too.
So my plan is to make them choose from a file from their computer, and then they choose the squd that they belong to. After this they will see a preview of the picutre and they can save it to their computer to later use it on the game.
I know that you can draw image with a Graphic or Graphic2D on the background of a component, but then when I want to save it to a file, How I do that?
Use JFileChooser#showSaveDialog() to ask user to select/specify a file to save and then use ImageIO#write() to write the BufferedImage to the file.
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
ImageIO.write(bufferedImage, "JPEG", fileChooser.getSelectedFile());
} else {
// User pressed cancel.
}
The applet needs however to be signed to avoid the enduser being scared by security warnings.
Digital code signing is not required for an applet deployed using a Plug-In 2 (PI2 - 1.6.0_10+) architecture JRE. In a PI2 JRE, an embedded applet can access all the services normally only available to Java Web Start apps.
The services of interest to this applet would be the FileOpenService (FOS), and the PersistenceService (PS). The FOS could be used to allow the user to navigate to a File (or rather - a FileContents) object and obtain streams from it. Once the user is happy with the cropped image, save in to the PS for later retrieval (using ImageIO, as already mentioned).
here is the notepad code where u can save the contents and also if u convert the text into an image.so try going through it
/*Arpana*/
mport javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.*;
public class Notepad extends JFrame implements ActionListener {
private TextArea textArea = new TextArea("", 0,0, TextArea.SCROLLBARS_VERTICAL_ONLY);
private MenuBar menuBar = new MenuBar(); // first, create a MenuBar item
private Menu file = new Menu(); // our File menu
// what's going in File? let's see...
private MenuItem openFile = new MenuItem(); // an open option
private MenuItem saveFile = new MenuItem(); // a save option
private MenuItem close = new MenuItem(); // and a close option!
public Notepad() {
this.setSize(500, 300); // set the initial size of the window
this.setTitle("Java Notepad Tutorial"); // set the title of the window
setDefaultCloseOperation(EXIT_ON_CLOSE); // set the default close operation (exit when it gets closed)
this.textArea.setFont(new Font("Century Gothic", Font.BOLD, 12)); // set a default font for the TextArea
// this is why we didn't have to worry about the size of the TextArea!
this.getContentPane().setLayout(new BorderLayout()); // the BorderLayout bit makes it fill it automatically
this.getContentPane().add(textArea);
// add our menu bar into the GUI
this.setMenuBar(this.menuBar);
this.menuBar.add(this.file); // we'll configure this later
// first off, the design of the menuBar itself. Pretty simple, all we need to do
// is add a couple of menus, which will be populated later on
this.file.setLabel("File");
// now it's time to work with the menu. I'm only going to add a basic File menu
// but you could add more!
// now we can start working on the content of the menu~ this gets a little repetitive,
// so please bare with me!
// time for the repetitive stuff. let's add the "Open" option
this.openFile.setLabel("Open"); // set the label of the menu item
this.openFile.addActionListener(this); // add an action listener (so we know when it's been clicked
this.openFile.setShortcut(new MenuShortcut(KeyEvent.VK_O, false)); // set a keyboard shortcut
this.file.add(this.openFile); // add it to the "File" menu
// and the save...
this.saveFile.setLabel("Save");
this.saveFile.addActionListener(this);
this.saveFile.setShortcut(new MenuShortcut(KeyEvent.VK_S, false));
this.file.add(this.saveFile);
// and finally, the close option
this.close.setLabel("Close");
// along with our "CTRL+F4" shortcut to close the window, we also have
// the default closer, as stated at the beginning of this tutorial.
// this means that we actually have TWO shortcuts to close:
// 1) the default close operation (example, Alt+F4 on Windows)
// 2) CTRL+F4, which we are about to define now: (this one will appear in the label)
this.close.setShortcut(new MenuShortcut(KeyEvent.VK_F4, false));
this.close.addActionListener(this);
this.file.add(this.close);
}
public void actionPerformed (ActionEvent e) {
// if the source of the event was our "close" option
if (e.getSource() == this.close)
this.dispose(); // dispose all resources and close the application
// if the source was the "open" option
else if (e.getSource() == this.openFile) {
JFileChooser open = new JFileChooser(); // open up a file chooser (a dialog for the user to browse files to open)
int option = open.showOpenDialog(this); // get the option that the user selected (approve or cancel)
// NOTE: because we are OPENing a file, we call showOpenDialog~
// if the user clicked OK, we have "APPROVE_OPTION"
// so we want to open the file
if (option == JFileChooser.APPROVE_OPTION) {
this.textArea.setText(""); // clear the TextArea before applying the file contents
try {
// create a scanner to read the file (getSelectedFile().getPath() will get the path to the file)
Scanner scan = new Scanner(new FileReader(open.getSelectedFile().getPath()));
while (scan.hasNext()) // while there's still something to read
this.textArea.append(scan.nextLine() + "\n"); // append the line to the TextArea
} catch (Exception ex) { // catch any exceptions, and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
// and lastly, if the source of the event was the "save" option
else if (e.getSource() == this.saveFile) {
JFileChooser save = new JFileChooser(); // again, open a file chooser
int option = save.showSaveDialog(this); // similar to the open file, only this time we call
// showSaveDialog instead of showOpenDialog
// if the user clicked OK (and not cancel)
if (option == JFileChooser.APPROVE_OPTION) {
try {
// create a buffered writer to write to a file
BufferedWriter out = new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));
out.write(this.textArea.getText()); // write the contents of the TextArea to the file
out.close(); // close the file stream
} catch (Exception ex) { // again, catch any exceptions and...
// ...write to the debug console
System.out.println(ex.getMessage());
}
}
}
}
// the main method, for actually creating our notepad and setting it to visible.
public static void main(String args[]) {
Notepad app = new Notepad();
app.setVisible(true);
}
}
I think I'd be inclined to interact the Java with Javascript on the same page, and give an 'export' button which serialises it to PNG locally, and offers it as a download (should be possible all without the user needing to refresh the page or mess around). There are some interesting comments in this previous question: Java applet - saving an image in a png format
The notepad program which i have posted just above this post gives the load image of any type and also to save image of any type....
so you cab refer the same code to load the image and save the image