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!
Related
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.
I've a simple GUI file which is here:
I want to update the Label text each time when new file is selected
But when I am selecting any file, it is overlapping on the existing Jlabel text, so, please help me how do I update my JLabel text.
Here is my code:
protected static void excelButtonAction(){
excelReturnVal = fc.showOpenDialog(excelButton);
if(excelReturnVal==JFileChooser.APPROVE_OPTION){
FileValidation.excelFileValidation(fc);
System.out.println(FileValidation.getName() );
if(status==JFileChooser.CANCEL_OPTION){
}else{
fileName=FileValidation.getName();
FileValidation.updatemylabel(fileName);
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
}
} else{
System.out.println("Open command cancelled by user." + newline);
}
}
public static void updatemylabel(String exfileName){
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
File curFile = chooser.getSelectedFile();
}else if(JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())){
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
File[] files = chooser.getSelectedFiles();
}
}
});
excelFileName = new JLabel(fileName);
excelFileName.setText(fileName);
excelFileName.setBounds(140, 67, 350, 30);
excelFileName.setFont(new Font("Myriad Pro",Font.PLAIN,10));
panel.add(excelFileName);
panel.revalidate();
panel.repaint();
existingText=exfileName;
}
Let me know if any further information is required to resolve my issue.
Thanks in advance for your co-operateion.
Your code creates a new JLabel instance every time. You need to create an instance once, store it in a field of your class, and call setText() whenever you need to update it.
You can have a look at the following for better understanding of labels in java :
How to Use Labels
setText
public void setText(String text)
Defines the single line of text this component will display. If the value of text is null or empty string, nothing is displayed.
The default value of this property is null.
This is a JavaBeans bound property.
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)
How do you display the contents of a text file in a TextArea when your using JFileChooser.
You have to read official Oracle's JTextArea tutorial
Especially method JTextArea.read(fileSelectedFromJFileChooser) , maybe right way in this case
Please have a look at Reading, Writing and Creating Files Tutorials
Here find one example program, for your help, though if the file to be read is long, then always take the help of SwingWorker :
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReadFileExample
{
private BufferedReader input;
private String line;
private JFileChooser fc;
public ReadFileExample()
{
line = new String();
fc = new JFileChooser();
}
private void displayGUI()
{
final JFrame frame = new JFrame("Read File Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextArea tarea = new JTextArea(10, 10);
JButton readButton = new JButton("OPEN FILE");
readButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
try
{
input = new BufferedReader(
new InputStreamReader(
new FileInputStream(
file)));
tarea.read(input, "READING FILE :-)");
}
catch(Exception e)
{
e.printStackTrace();
}
} else {
System.out.println("Operation is CANCELLED :(");
}
}
});
frame.getContentPane().add(tarea, BorderLayout.CENTER);
frame.getContentPane().add(readButton, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ReadFileExample().displayGUI();
}
});
}
}
Your question is unclear, but I am assuming you want to add the JTextArea to the JFileChooser so that it can act like a file preview panel.
You can add a JTextArea to the JFileChooser by using the setAccessory() method.
This tutorial on JFileChooser shows how to do something similar where the accessory displays an image from the file rather than text from the file.
You will need to be careful to deal properly with files that don't contain text, or which are too large, or which cannot be opened due to permission, etc. It will take a good bit of effort to get it right.
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.