Create file and save it to an dynamic storage - java

I create a file like this:
PrintWriter out = new PrintWriter(
new FileOutputStream(
new File("C:/Users/.../Desktop/Server Recipe Log.txt"),
true));
out.println("serverText");
out.close();
But I don't want to save the file on my desktop - I want to open the save as dialog to choose the place where I want to save the file.
I have tried out some tutorials with Frames but I don't want to create any frame, I want to use the native system dialog.

..want to use the native system dialog.
You are using the wrong language. The closest Java offers is a java.awt.FileDialog or a javax.swing.JFileChooser using the native PLAF.
E.G.
import java.awt.*;
import javax.swing.*;
class FileDialogs {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
FileDialog fd = new FileDialog((Frame)null);
fd.setVisible(true);
JFileChooser fc = new JFileChooser();
fc.showSaveDialog(null);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}

JFileChooser jl = new JFileChooser();
jl.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int save = jl.showSaveDialog(null);
if (JFileChooser.APPROVE_OPTION == save){
PrintWriter out = new PrintWriter(
new FileOutputStream(
new File(jl.getSelectedFile().getAbsolutePath()+"/name.txt"),
true));
out.println("serverText");
out.close();
}

Related

java actionListener: retrieve TextField in a separate thread

i have a Frame which look like this:
public class Load_Frame extends JFrame implements ActionListener{
private JButton uploadButton, downloadButton;
private JTextField uploadField;
private String filename;
private Client client;
public Load_Frame(String username, Socket socket) {
this.client = new Client(username, socket);
uploadField = new JTextField ();
uploadField.setBounds(60,100,450,30);
uploadButton = new JButton ("Upload");
uploadButton.setBounds(410,150,100,30);
uploadButton.addActionListener(this);
downloadButton = new JButton ("Download");
downloadButton.setBounds(390,300,120,30);
downloadButton.addActionListener(this);
this.add(uploadField);
this.add(uploadButton);
this.add(downloadButton);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
//Upload:
if (e.getSource()== uploadButton) {
this.filename = uploadField.getText();
File file = new File(filename);
client.upload(file);
}
//Download
else if (e.getSource()== downloadButton) {
filename = (String) filesList.getSelectedItem();
client.download(filename);
}
}
My problem is: i have been said that the frame and the "process" should be separated in different thread, so that when the process fail the frame don't freeze. So i need my Client to be a new thread.
But then, i still need acess to those "upload" and "download" button. I've read that i can easily do that like it:
public class Client implements Runnable, ActionListener{
...
public void actionPerformed(ActionEvent e){
if(e.getSource() == uploadButton){
File file = new File(filename); //how can i retrieve the filename??
upload(file);
}
}
and i'll just need to add another actionListener in my Frame class like that:
uploadButton.addActionListener(client);
(same for download of course)
My prolem is: how can i get the filename, the text written in the TextField of my Frame?? Should i give this TextField as a parameter for my client ? This will make the code look weird, and by weird i mean not very logical, so i hope there is another way to do so.
You can create two thread one for download and one for upload like below
public void actionPerformed(ActionEvent e){
if(e.getSource()==uploadButton){
new Thread(){
public void run(){
this.filename = uploadField.getText();
File file = new File(filename);
client.upload(file);
}
}.start();
}
else if(e.getSource() == downloadButton){
new Thread(){
public void run(){
this.filename = downloadField.getText();
File file = new File(filename);
client.download(file);
}
}.start();
}
}

How to read file in Java only after JFrame is displayed?

I'm using Java Swing. Initially I want to read a file (which is quite big). So the frame gets displayed after the file is completely. Whereas I want the frame to first load (displayed) and then the file should be read.
class Passwd {
JFrame jfrm;
// other elements
Passwd() {
start();
// Display frame.
jfrm.setVisible(true);
}
public void start() {
// Create a new JFrame container.
jfrm = new JFrame("Password Predictability & Strength Measure");
// Specify FlowLayout for the layout manager.
//jfrm.setLayout(new FlowLayout());
jfrm.setLayout(null);
// Give the frame an initial size.
jfrm.setSize(450, 300);
// align window to center of screen
jfrm.setLocationRelativeTo(null);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// some elements
File file = new File("file.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// operation
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Passwd();
}
});
}
}
How can I read the file after the frame is displayed?
The JFrame should display immediately, so that's not the problem. The problem is that you're reading in the file on the Swing event thread, and this blocks its ability to display the JFrame. The solution is to not do this, to instead read the file in a background thread, such as via a SwingWorker. This way the JFrame can display unimpeded, and the file reading will not interfere with Swing functioning.
So if the file reading will not change the state of Swing components, use a simple background thread:
new Thread(() -> {
File file = new File("file.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// operation
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
If the reading in will change the state of the GUI as the reading occurs, again, use a SwingWorker.
Side issue: avoid using null layouts as they'll come back to bite you.

JFileChooser confusion

I have to write a program that essentially makes a report card, but it cannot do so until until it reads in a file either through command line arguments or by the user picking one from their browser, which means I need to use JFileChooser. I have the GUI set-up for the JFileChooser but that's all I can figure out. The dialog window opens when I click open but after picking a file the window I created (GUI) does not close. Also the program runs through all of my other methods before a file is even loaded causing other problems. I tried using a do-while loop but it just runs through the loop before I can ever open a file.
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MP1 extends JFrame implements java.awt.event.ActionListener{
static StudentAssignments geen165 = new StudentAssignments();
static boolean fileReady = false;
/**
* #param args the command line arguments
*/
public static void main(String [] args) {
do{
if(args.length == 0 || args[0].isEmpty()){//reads in input from file
//select
MP1 doIt = new MP1();
doIt.setVisible(true);
}
else{
geen165.readGradeFile(args[0]);//reads in input file from command
//argument
}
}while(!fileReady);
//test methods
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
geen165.addAssignments(3, 98, 100);
geen165.saveGradeFile("NewGrades.txt");
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
geen165.removeAssignment(0, 2);
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
}
//JFile Chooser GUI
public MP1(){
prepareGui();
}
private void prepareGui(){
setSize(500,500);
Container window = getContentPane();
window.setLayout(new FlowLayout());
JButton open = new JButton("Open");
JButton cancel = new JButton("Cancel");
JLabel status = new JLabel("You've selected: ");
//sets file when open is pressed
open.addActionListener((ActionEvent e) -> {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(window);
if(returnVal == JFileChooser.APPROVE_OPTION){
File fileName = chooser.getSelectedFile();
status.setText("You've selected: " + fileName.getName());
geen165.readGradeFile(fileName.getName());
fileReady=true;
}
});
//exits program if cancel is pressed
cancel.addActionListener((ActionEvent e) -> {
System.exit(1);
});
window.add(open);
window.add(cancel);
window.add(status);
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change
//body of generated methods, choose Tools | Templates.
}
}
Any suggestions?
You are complicating a simple issue. There is no need for you to build a window and everything only to use JFileChooser. A simple solution that works is
import javax.swing.*;
public class MP1 extends JFrame {
public static void main(String[] args) {
String myFile="";
if (args.length == 0 || args[0].isEmpty()) {//reads in input from file
//select
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
if (returnVal!=JOptionPane.CANCEL_OPTION) {
myFile = chooser.getSelectedFile().getPath();
} else {
JOptionPane.showMessageDialog(null, "Thanks for playing!");
System.exit(0);
}
} else {
myFile = args[0];
}
JOptionPane.showMessageDialog(null, "You have selected "+myFile+". Go play!");
}
}
Notice that I check whether there is a parameter. If not, I immediately go and execute the JFileChooser. There is no need for overhead.
I removed all your class activity, because I do not have the files.
BTW, I have not tested it, but I believe that your problem comes from your new frame not being modal. Hence, the boolean variable is changed before you can do anything. But that is just an idea.
I think you need to know how JFileChooser works.
JFileChooser fc = new JFileChooser();
int optionSelected = fc.showOpenDialog(YourClassName.this);
if (optionSelected == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
... // Do what you want with the file
}
JFileChooser

Can't interact with JFileChooser window, not clickable or closeble

In my code I am asking the user to choose an image. My JFileChooser window worked fine. Then I restarted my computer and now whenever that window comes up it is not clickable in any way. I can't open a file, I can't cancel, I can't chooser folders or files. Here is the necessary code.
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
jfc.setFileFilter(filter);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setVisible(true);
int ret = jfc.showOpenDialog(null);
if (ret == JFileChooser.CANCEL_OPTION) {
return;
}
File file_1 = jfc.getSelectedFile();
file_path = file_1.getAbsolutePath();
Breakpoints show that the program never leaves this line:
int ret = jfc.showOpenDialog(null);
As I said the same exact code was working fine moments ago. Not sure what is causing this situation.
In my main program I click "Add image" which calls the previously mentioned code. I try clicking on the window "Open" opened by "showOpenDialog" but it doesn't matter where I click. Nothing changes. The main program resumes once I close the "Open" window from my task manager. Also in my task manager "Open" window doesn't say not responding, it looks fine and closes at an instance and furthermore inside the text field the text cursor is blinking.
EDIT: Same exact code works on a separate project that consists of only this code.
EDIT 2: Some additional codes.
Here is the complete load_file() function.
public class Image {
private static String file_path;
private static ImageFrame frame;
public static boolean isImgLoaded = false;
public static void load_file(){
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "jpeg");
jfc.setFileFilter(filter);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setVisible(true);
int ret = jfc.showOpenDialog(null);
if (ret == JFileChooser.CANCEL_OPTION) {
return;
}
File file_1 = jfc.getSelectedFile();
file_path = file_1.getAbsolutePath();
ImageFrame frm = new ImageFrame();
frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frm.setVisible(true);
frame = frm;
isImgLoaded = frame.get_component().is_img_loaded();
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
closeFrame();
}
});
}
Here is the button code that calls the function when pressed. shlErgo is my shell that the UI is built on.
Button btnAddImage = new Button(shlErgo, SWT.NONE);
btnAddImage.setBounds(230, 10, 75, 25);
btnAddImage.setText("Add Image");
btnAddImage.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
if (!Image.isImgLoaded){
Image.load_file();
}
else{
Error.translate(2);
}
}
});

JPanel doesn't load in JFrame

I have a problem showing my progress bar when reading a file in Java.
All works as intended, user choose a file, the program must show the progress bar (but it loads an empty blank frame), process the file and then load the results on another window.
I can't get the program to show the content of the progress bar dialog.
A little help here would be really appreciated.
Here is the code of the 3 methods involved.
//this method reads the file
public void processFile(File arch) {
aFile = arch;
Thread threadForSearch = new Thread() {
#Override
public void run() {
try{
listaProveedoresTango = controladoraConsultas.traerProveedores();
listaProveedoresAFIP = new LinkedList();
BufferedReader data = new BufferedReader(new FileReader(aFile));
String s;
while ((s = data.readLine()) != null) {
//long task
}
data.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
};
interfacesController.loadProgressBar();
threadForSearch.start();
try {
threadForSearch.join();
} catch (InterruptedException ex) {
Logger.getLogger(Controladora.class.getName()).log(Level.SEVERE, null, ex);
}
this.interfacesController.closeProgressBar();
this.interfacesController.loadResults(someStuff);
}
//load a progress bar
public void loadProgressBar(){
JProgressBar pb = new JProgressBar(0,100);
pb.setPreferredSize(new Dimension(175,20));
pb.setString("Processing Data");
pb.setStringPainted(true);
pb.setIndeterminate(true);
JLabel infoLabel = new JLabel("Reading File: ");
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent evt) {
exitSystem();
}
});
cancelButton.setVerticalAlignment(SwingConstants.CENTER);
JPanel center_panel = new JPanel();
center_panel.add(infoLabel);
center_panel.add(pb);
center_panel.add(cancelButton);
center_panel.setLayout(new BoxLayout(center_panel,BoxLayout.Y_AXIS));
dialog = new JDialog((JFrame)null, "Processing ...");
dialog.getContentPane().add(center_panel, BorderLayout.CENTER);
dialog.setSize(100, 100);
dialog.setLocationRelativeTo(null);
dialog.pack();
dialog.setVisible(true);
}
//close the open progress bar
public void closeProgressBar(){
this.dialog.dispose();
}
Solved with SwingWorker, i post a summarized code:
public void processFile(File arch) {
aFile = arch;
final SwingWorker searchOnFile = new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
try{
BufferedReader data = new BufferedReader(new FileReader(aFile));
String s;
while ((s = data.readLine()) != null) {
//long task
}
data.close();
}catch (Exception e){ //Catch exception if any
System.err.println("Error: " + e.getMessage());
}
interfacesController.closeProgressBar();
interfacesController.loadResults(someStuff);
return null;
}
};
interfacesController.showProgressBar();
searchOnFile.execute();
}
interfacesController contains all the methods to work with GUIs, showProgressBar() is used to show the bar and closeProgressBar() do the opposite. Thank you guys!
Short of more useful code, I suggest using a SwingWorker.
An abstract class to perform lengthy GUI-interaction tasks in a background thread. Several background threads can be used to execute such tasks. ..
Given the nature of the task, you might also look at ProgressMonitorInputStream.
..creates a progress monitor to monitor the progress of reading the input stream. If it's taking a while, a ProgressDialog will be popped up to inform the user. If the user hits the Cancel button an InterruptedIOException will be thrown on the next read. All the right cleanup is done when the stream is closed.

Categories

Resources