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()
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);
}
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?
}
}
});
I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.
Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
I am working on a text editor in Java as a fun side project. When I exported the project, I converted to executable JAR file to ".exe" so that I could set the text editor as the default program to open ".txt" files. I can run the ".exe" and write text and then save the file, and the file saves, but the contents of the file are not saved when I try to open the file with the text editor; however, I can open the same file with notepad, and the contents of the file show. The file saves fine in Eclipse. What do I need to fix so that the file contents are shown when I try to open them with my text editor?
Here is my code:
public class Open extends JFrame implements KeyListener {
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JMenuBar menuBar = new JMenuBar();
JMenu menu;
JMenuItem item;
Font systemFont;
public Open() {
systemFont = new Font("Times New Roman", Font.PLAIN, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(false);
textArea.setFont(systemFont);
panel.setLayout(new BorderLayout());
panel.add(scrollPane);
add(panel);
menu = new JMenu("File");
item = new JMenuItem("Save As");
item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
menu.add(item);
menuBar.add(menu);
menu = new JMenu("Edit");
item = new JMenuItem("Undo");
menu.add(item);
menu.add(item);
menuBar.add(menu);
add("North", menuBar);
setLookAndFeel();
frameDetails("Text Editor");
}
public void frameDetails(String title) {
setSize(700, 500);
setLocationRelativeTo(null);
setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setLookAndFeel() {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Open editor = new Open();
}
}
Here is the bit of code with the save button:
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
You are never reading the text file. In order to do that, Use something like this
public void loadFile(JTextArea area, String path, String file)
{
try
{
area.read(new FileReader(path + file), "Default");
}
catch(IOException e)
{
e.printStackTrace();
}
}
Note: You don't have to have this in a method. You could just use the try - catch code
To act as a default text editor, your program needs to accept a file name as the argument to main (String[] args). It should verify the file exists, then open it, read its contents, and close it.
Also, when you save a file you should rename the former version to "name.bak" or "name~" before overwriting it with the new version, in case something goes wrong during the save.
I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.