runEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File inputFile = new File("/Users/aktasberk/Desktop/hey");
File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
File decryptedFile = new File("/Users/aktasberk/Desktop/Decrypted_"+inputFile.getName());
try {
String key = "16BitKeyIsHere16";
CryptoUtils.encrypt(key, inputFile, encryptedFile);
CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
} catch (CryptoException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
});
Okay so I have an encryption&decryption project, the encrypting and decrypting works fine but I have some problems using FileInputStream to get the file from directory, I have a browse button to do that but could not make it work, so as you can see in the code I get the input file manually.
Below here is my browse button opening up a file dialog to let me choose a file.
browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
if (selectedFile != null) {
encryptPath.setText(selectedFile.getPath());
primaryStage.show();
}
}
});
I need to get the file from browse button instead of declaring it manually in the code, I can be more specific if info is needed, thanks.
Delete local:
File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
Make global
File encryptedFile;
Then:
browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
if (selectedFile != null) {
encryptPath.setText(selectedFile.getPath());
encryptedFile = selectedFile;//Add This!
primaryStage.show();//Not sure why this is here?
}
}
});
Related
I have two buttons in a menubar that contains both a save and save as button. However, I currently have the code for both of them the same and it does the save as currently with prompting the user where they want to save. I want the save button to only save without prompting for the dialog unless the file doesn't yet exist.
I've tried fiddling around with the code to try and figure out a workaround, but have not figure it out.
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
The code currently does the exact same save function for each save button. I want it to only prompt for the save as button.
You need to have a File instance field in your class that is initially assigned to null. When you read in a File or when you do your first save, then this field is assigned to that File. When the save button is pressed, then you check if the field is null, and if so, show the dialog as you would for the save-as button. If the field is not null, then you simply write the file to disk using the data that you have and that File.
for example (code not tested):
// a private instance field
private File myFile = null;
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (myFile == null) {
saveAs();
} else {
writeFile(myFile);
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
saveAs();
}
});
private void writeFile(File file) {
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
private void saveAs() {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
myFile = file; // !!
writeFile(file);
}
Essentially, I'm trying to collect data for a string and use it in another method. Whatever I've tried hasn't seemed to work. Please check out my code and tell me what to do.
I've tried to declare the string as a public string, but since it is in a method I can't.
My goal is to transfer the string "application_1" to button3's setOnAction method.
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("myDesktop");
window.setOnCloseRequest(e -> closeProgram());
button = new Button("Setup MyDesktop");
button3 = new Button("Start Test Application");
button2 = new Button("Choose Wheel Applications");
button2.setOnAction(e -> {
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null, "Please select a file.");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
String application_1 = filename.getName();
if (application_1.endsWith(".exe")) {
System.out.println("File successfully chosen!");
} else {
System.out.println("File is not an application!");
System.out.println("Please choose another file!");
System.out.println("Issue Alert Box here...");
}
if (application_1 == null) {
System.out.println("No file selected!");
}
});
button.setOnAction(e -> {
AlertBox.display("Alert", "Save file?");
});
button3.setOnAction(e -> {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("name_of_file");
} catch (IOException e1) {
e1.printStackTrace();
}
});
I want the string to be able to be used by the code
button3.setOnAction(e -> {
// code
});
Should work:
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("myDesktop");
window.setOnCloseRequest(e -> closeProgram());
String application_1 = "";
button = new Button("Setup MyDesktop");
button3 = new Button("Start Test Application");
button2 = new Button("Choose Wheel Applications");
button2.setOnAction(e -> {
JFileChooser jfc = new JFileChooser();
jfc.showDialog(null, "Please select a file.");
jfc.setVisible(true);
File filename = jfc.getSelectedFile();
application_1 = filename.getName();
if (application_1.endsWith(".exe")) {
System.out.println("File successfully chosen!");
} else {
System.out.println("File is not an application!");
System.out.println("Please choose another file!");
System.out.println("Issue Alert Box here...");
}
if (application_1 == null) {
System.out.println("No file selected!");
}
});
button.setOnAction(e -> {
AlertBox.display("Alert", "Save file?");
});
button3.setOnAction(e -> {
Runtime runtime = Runtime.getRuntime();
System.out.println(application_1); //here you can use the variable
try {
Process process = runtime.exec("name_of_file");
} catch (IOException e1) {
e1.printStackTrace();
}
});
Since you don't have control over the actual event that's created when the button is hit you cannot pass it directly (well, maybe you could add a tag to the button or something similar - I never used javafx).
But nothing prevents you from introducing an object-level variable to hold your string(s).
class YourClass {
private String myString = "";
public void start(Stage primaryStage) throws Exception {
// ...
button2.setOnAction(e -> {
this.myString = "application_1";
});
// ...
button3.setOnAction(e -> {
System.out.println(this.myString);
});
}
}
Alternatively, if your variable is final or effectively final you can just use it in your anonymous function:
class YourClass {
public void start(Stage primaryStage) throws Exception {
// ...
final String myString = "application_1";
// ...
button3.setOnAction(e -> {
System.out.println(myString);
});
}
}
So am trying to make a button where it opens a FileChoser to import an image .
My probleme is :
1-I want the fileChoser to display only images-files(.jpg ...).
2-When the FileOpener opens , the other windows should be Disabled until the
FileOpener is disposed . In my case , they are disabled but when I click on them my programe crashes for some reason .
3-If there is a better FileOpener it will be welcomed , this si not mine I found it on the net .
Here's my source code :
public class FileOpener {
private JFileChooser file_chooser = new JFileChooser();
StringBuilder path = new StringBuilder();
public File choosed() {
File file = null;
if(file_chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = file_chooser.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Fail");
e.printStackTrace();;
}
while(input.hasNext()) {
path.append(input.nextLine());
}
input.close();
}
return file;
}
public String getPath() {
return path.toString();
}
}
And here's my call (Where there is a probleme is the enable-disable window) :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
shell.setEnabled(false);
FileOpener v = new FileOpener();
File file = v.choosed();
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
shell.setEnabled(true);
}
});
Notice that this code works , but am trying just to fix the bugs,the "ScaleImage" fonction reScale the chosen Image to fit my label.
I managed to fix the Enable-disable problem simply by removing all what was interfering with the shell :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileOpener v = new FileOpener();
File file = v.choosed();
shell.forceActive();
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
}
});
I fixed completly my probleme by using FileDialog :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog test = new FileDialog(shell);
test.open();
File file = new File(test.getFilterPath()+"\\"+test.getFileName());
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
}
});
Thanks for greg-449 for the answer .I didn't know how to exactly work with the new GUI but to get the file path :
test.getFilterPath()+"\\"+test.getFileName()
I have to copy the chosen image to the application folder. The image will be chosen by clicking the button. Here is the code (ActionListener) for that Button
imageButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String outPath = new java.io.File("").getAbsolutePath();
fileChooser.showOpenDialog(null);
File pic = fileChooser.getSelectedFile();
String inPath = pic.getPath();
try {
Utils.copyFile(inPath, outPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
The method copyFile is this:
public static void copyFile(String inPath, String outPath) throws IOException
{
FileInputStream fis=new FileInputStream(new File(inPath));
FileOutputStream fos=new FileOutputStream(new File(outPath));
int c;
while((c=fis.read())!=-1)
{
fos.write(c);
}
}
It gives "File not Found Exception" in Blue and in red color it shows "Access is Denied" when i select the image. I am not sure where the problem is there in my code.
Here I have text area called sourceTx in which I drag and drop files, then I read content of that file with BufferedReader. As you can see from bellow code I set file from which I am reading content with absolutepath.
So, when I drag an drop some .txt file it works, it reads content and put it in text area, but when I also drag and drop some folder for example it also reads some content and put it in text area.
So I want set this drag and drop to read only .txt files? How I can get that?
Here is code of that method:
public void dragDrop(){
sourceTx.setOnDragOver(new EventHandler <DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if(db.hasFiles()){
event.acceptTransferModes(TransferMode.ANY);
for(File file:db.getFiles()){
String absolutePath = file.getAbsolutePath();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath)));
String line = null;
String text = "";
String nl = System.getProperty("line.separator", "\n");
while((line = br.readLine()) != null)
text += line + nl;
sourceTx.setText( text.trim() );
} catch (Exception e) {
MessageBox.show(MessageBoxType.ERROR, I18n.localize("File Error"), I18n.localize("Error while reading content from selected file"));
} finally{
if(br != null)
try {
br.close();
} catch (Exception e) {}
}
}
}else{
event.setDropCompleted(false);
}
event.consume();
}
});
}
Hi there try to read your file with recursion
...
for (File file : db.getFiles()) {
sourceTx.setText(handleFile(file));
}
...
private String handleFile(File file) {
String ret = "";
if (file.isDirectory()) {
for (File f : file.listFiles()) {
ret.concat(handleFile(f));
}
} else {
/*this is your filereader*/
String absolutePath = file.getAbsolutePath();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath)));
String line = null;
String text = "";
String nl = System.getProperty("line.separator", "\n");
while ((line = br.readLine()) != null)
text += line + nl;
ret.concat(text.trim());
} catch (Exception e) {
MessageBox.show(MessageBoxType.ERROR, I18n.localize("File Error"), I18n.localize("Error while reading content from selected file"));
} finally {
if (br != null)
try {
br.close();
} catch (Exception e) {
}
}
}
return ret;
}
I found a good resource online on using drag and drop.
Here are some classes/things that you might want to investigate:
java.awt.dnd.*
I practically copied this from a tutorial online but here is some code (not mine, but tested and it works):
public class MyFrame extends JFrame
{
// insert other code here
JLabel myLabel = new JLabel("My stuff here");
// Create the drag and drop listener
MyDragDropListener myDragDropListener = new MyDragDropListener(this);
// Connect the label with a drag and drop listener
new DropTarget(myLabel, myDragDropListener);
// then just add the label
// also have a method something like "get" which will be used so that the listener can send
// the list of files dropped here, and you can process it here
}
Now for the MyDragDropListener.
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.io.File;
import java.util.List;
public class MyDragDropListener implements DropTargetListener
{
MyFrame frame; // initialize in a constructor that takes in the frame
#Override
public void dragEnter(DropTargetDragEvent event) {
}
#Override
public void dragExit(DropTargetEvent event) {
}
#Override
public void dragOver(DropTargetDragEvent event) {
}
#Override
public void dropActionChanged(DropTargetDragEvent event) {
}
#Override
public void drop(DropTargetDropEvent event)
{
// This is the main chunk of the drag and drop.
event.acceptDrop(DnDConstants.ACTION_COPY);
Transferable transferable = event.getTransferable();
DataFlavor[] flavors = transferable.getTransferDataFlavors();
for(DataFlavor flavor : flavors)
{
if(flavor.isFlavorJavaFileListType())
{
List myFiles = (List) transferable.getTransferData(flavor);
frame.get(myFiles);
}
}
}
}
You can use this to create a JFrame to drag and drop the files, then check if the filename contains ".txt" ( I am not sure if Java has methods of determining the type of file even if it has no extensions .) If it contains ".txt" then you can open it in the TextArea.
If anyone can please help me find the original tutorial/site, I would really appreciate it. Also sorry for the formatting of the answer.