How to draw image using FileDialog in Java - java

Need to display selected in FileDialog image, but thats somewhy didnt work. When i try to choose image it throws exception javax.imageio.IIOException: Can't create an ImageInputStream!
I think problem is in getDirectory() , but dont know how to fix.
public ImageShow() throws IOException {
super("Pictures");
setSize(1024,768);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonOpen = new JButton("Open file");
buttonPanel.add(buttonOpen);
actions();
fileDialog();
add(buttonPanel);
image = ImageIO.read(new File(fd.getDirectory()));
imageLabel = new JLabel(new ImageIcon(image));
buttonPanel.add(imageLabel);
}
public void fileDialog() {
fd = new FileDialog(new JFrame(), "Choose file");
fd.setVisible(true);
}
public void actions() {
buttonOpen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fileDialog();
}
});
}
}

image = ImageIO.read(new File(fd.getDirectory()));
A directory is not an image! Try instead getFile() which:
Gets the selected file of this file dialog. If the user selected CANCEL, the returned file is null.
But as I said in comments..
Use the Swing based JFileChooser rather than the AWT based FileDialog.
And be sure to consult the avialable documentation when using methods.

Related

Upload image to server from Java

Follow a small Java code to select an image from a folder. What I would like is to know how to upload it to a server, I have always uploaded images from javascript or jquery or php too. Use a AngularJS frameworks and also to upload images Ionic from mobile devices to my server, I am now working directly in Java and have some doubts. On issues of time, I would like to know how is the best way to upload an image, bits or base64? And if they could help me with this conversion would appreciate. I'm new to Java and I'm just practicing. Regards!
My code :
public class UI extends JFrame {
JButton buttonBrowse;
JButton buttonUpload;
JLabel label;
public UI(){
super("Set Picture Into A JLabel Using JFileChooser In Java");
buttonBrowse = new JButton("Browse");
buttonUpload = new JButton("Upload");
buttonBrowse.setBounds(300,300,100,40);
buttonUpload.setBounds(400, 300, 100, 40);
label = new JLabel();
label.setBounds(10,10,670,250);
add(buttonBrowse);
add(buttonUpload);
add(label);
buttonBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
//filter the files
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
//if the user click on save in Jfilechooser
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
System.out.println(path);
label.setIcon(ResizeImage(path));
}
//if the user click on save in Jfilechooser
else if(result == JFileChooser.CANCEL_OPTION){
System.out.println("No File Select");
}
}
});
buttonUpload.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(700,400);
setVisible(true);
}
// Methode to resize imageIcon with the same size of a Jlabel
public ImageIcon ResizeImage(String ImagePath)
{
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
public static void main(String[] args){
new UI();
}
}

Java Null Pointer When clicking JButton(Eclipse)

Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
JButton save,help,savePath;
//JTextArea text;
public EventListeners(){
window();
}
public void window(){
JFrame window = new JFrame();
window.setVisible(true);
window.setSize(650,500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10,50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500,500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20,100);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
} catch(IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
}
});
}
public static void main(String[] args) {
new EventListeners();
}
}
main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.
for example
you have declare instance variable
JButton save, help, savePath, saveFilePath;
inside constructor you are creating another local jbutton and initialize it so instance variable is null.
so instead of creating new one you should initialize instance field.
JButton saveFilePath = new JButton("File Path Save Settings"); // problem
saveFilePath = new JButton("File Path Save Settings"); // correct way
but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.
also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.
also you should call repaint() at last after you add all the component to a frame..
try to run this code
import javax.swing.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class EventListeners {
String textAreaValue;
String filePath;
String rememberedPath;
String rememberedPathDirectory;
//Global components
JTextField fileName, filePathSaveDirectory, savedFilePath;
JButton save, help, savePath, saveFilePath;
//JTextArea text;
public EventListeners() {
window();
}
public void window() {
JFrame window = new JFrame();
window.setSize(650, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
saveFilePath = new JButton("File Path Save Settings");
JTextArea ltext = new JTextArea(10, 50);
JLabel filler = new JLabel(" ");
JLabel lfileName = new JLabel("File Path(If error click help)");
JLabel lsaveFilePath = new JLabel("Save Path");
fileName = new JTextField(30);
save = new JButton("Save File");
help = new JButton("Help");
panel.add(lfileName);
panel.add(fileName);
panel.add(save);
panel.add(help);
panel.add(ltext);
panel.add(filler);
window.add(panel);
saveFilePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JOptionPane.showMessageDialog(null,"Hello world!");
JFrame windowB = new JFrame();
int windows = 2;
windowB.setVisible(true);
windowB.setSize(500, 500);
windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panelB = new JPanel();
JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
filePathSaveDirectory = new JTextField(20);
JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
savedFilePath = new JTextField(20);
savePath = new JButton("Save Settings");
panelB.add(lFilePathSaveDirectory);
panelB.add(filePathSaveDirectory);
panelB.add(lsavedFilePath);
panelB.add(savedFilePath);
panelB.add(savePath);
windowB.add(panelB);
System.out.println(savePath);
savePath.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rememberedPathDirectory = filePathSaveDirectory.getText();
rememberedPath = savedFilePath.getText();
try {
FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println(rememberedPath);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
}
});
}
});
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textAreaValue = ltext.getText();
filePath = fileName.getText();
try {
FileWriter fw = new FileWriter(filePath);
PrintWriter pw = new PrintWriter(fw);
pw.println(textAreaValue);
pw.close();
JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
} catch (IOException x) {
JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, " ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
}
});
panel.add(saveFilePath);
window.add(panel);
saveFilePath.setSize(20, 100);
window.setVisible(true);
}
public static void main(String[] args) {
new EventListeners();
}
}
You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like
public EventListeners(JButton save, JButton help, JButton saveFilePath) {
this.save = save;
this.help = help;
this.saveFilePath = saveFilePath);
}
Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.

How does this update a component without using an actionListener?

Code in Question
There isn't an actionListener for the image thumbnails, yet when clicked they update the image.
From this webpage.
Edit: I am currently importing images using JFileChooser and then creating a thumbnail and displaying the full image in a similar way to this, although not using ImageIcons. But would like to use this method so when I add an image it adds to the list and allows me to click the thumbnail to show that image.
However mine using actionListeners to change when something is pressed but this doesn't and can't understand the code where it does.
Thanks
Edit2:
Regarding the repaint option:
I have a class which extends component which then calls a repaint function.
public class Image extends Component {
private BufferedImage img;
//Print Image
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
I then have a class with all my Swing components which call methods from other classes.
Image importedImage = new Image(loadimageone.openFile());
Image scaledImage = new Image();
// Save image in Buffered Image array
images.add(importedImage.getImg());
// Display image
imagePanel.removeAll();
imagePanel.add(importedImage);
imagePanel.revalidate();
imagePanel.repaint();
previewPanel.add(scaledImage);
previewPanel.revalidate();
previewPanel.repaint();
If I remove the revalidate or repaint it wont' update the image on the screen.
Edit 3:
This is the code on how I implemented the dynamic buttons:
//Create thumbnail
private void createThumbnail(ImpImage image){
Algorithms a = new Algorithms();
ImpImage thumb = new ImpImage();
//Create Thumbnail
thumb.setImg(a.shrinkImage(image.getImg(), 75, 75));
//Create ImageIcon
ImageIcon icon = new ImageIcon(thumb.getImg());
//Create JButton
JButton iconButton = new JButton(icon);
//Create ActionListener
iconButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bottomBarLabel.setText("Clicked");
imagePanel.removeAll();
imagePanel.add(images.get(position)); //Needs Fixing
imagePanel.revalidate();
}
});
//Add to previewPanel
previewPanel.add(iconButton);
previewPanel.revalidate();
previewPanel.repaint();
}
It looks like it uses ThumbnailAction instead which extends AbstractAction (at the very bottom of the code). Swing components can use Actions instead of ActionListeners. The advantage of Actions is that buttons can share an Action and they will automatically use the same key-bindings etc.
http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
EDIT: I have added some code demonstrating that you do not need to explicitly repaint(). Give it a try.
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 1));
final JLabel iconLabel = new JLabel();
JButton button = new JButton("Put Image");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
iconLabel.setIcon(new ImageIcon(ImageIO.read(fc.getSelectedFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
panel.add(iconLabel);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
EDIT 2 (There is no Edit 2)
EDIT 3: Try this
public class MyActionListener implements ActionListener {
private JPanel imagePanel;
private Image image;
public MyActionListener(JPanel imagePanel, Image image) {
this.imagePanel = imagePanel;
this.image = image;
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Clicked");
imagePanel.removeAll();
imagePanel.add(image); //Needs Fixing
imagePanel.revalidate();
}
}

How to Display the Contents of a text file in a TextArea

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.

troubles with displaying image in window

I need to choose image with file open dialog and then show it in window. But When I choose image it is not shown in the window.
I've created class which create window with jmenubar and 1 jmenuitem. When I click on menuitem JfileChooser appears and then I choose some file. But then happens nothing.
I think the problem is in actionListener for JFileChooser(ImageFilter is a filter from docs java)
public Frame(){
//create bars and window
mainframe = new JFrame("Window");
mainframe.setVisible(true);
mainframe.setSize(300, 300);
menubar = new JMenuBar();
mainer = new JMenu("Menu");
menubar.add(mainer);
//create items
item = new JMenuItem("Open",KeyEvent.VK_T);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
item.getAccessibleContext().setAccessibleDescription("open image");
//action listener
item.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//open file dialog
choser = new JFileChooser();
choser.addChoosableFileFilter(new ImageFilter());
final int returnval = choser.showOpenDialog(menubar);
//action listener for JFileChooser
choser.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (returnval == JFileChooser.APPROVE_OPTION){
fc = choser.getSelectedFile();
try{
Panel panel = new ShowImage(fc.getName());
mainframe.getContentPane().add(panel);
}catch(Exception exc){};
}
}
}
);
}
}
);
mainer.add(item);
mainframe.setJMenuBar(menubar);
}
ShowImage class
class ShowImage extends Panel{
BufferedImage image;
public ShowImage(String imagename) throws IOException {
File input = new File(imagename);
image = ImageIO.read(input);
}
public void paint(Graphics g){
g.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
}
}
P.S another problem is that it shows nothing until I change size of the window.
Extend JPanel instead of Panel, and override paintComponent method, ie:
class ShowImage extends JPanel{
public void paintComponent(Graphics g){
...
}
}
Also, there is no need to addActionListener on JFileChooser, just check the return value and act accordingly, ie:
final int returnval = choser.showOpenDialog(menubar);
if (returnval == JFileChooser.APPROVE_OPTION){
...
}
Im pretty sure this line will cause problems:
Panel panel = new ShowImage(fc.getName());
getName() will return the name of the file. So for example if you choose a image with JFileChooser named image.jpg, getName will return "image.jpg". This will make the image only show if the file you select is stored in the root folder of your project. I would change getName() to getAbsoultePath() which will return the full patch (e.i c:\desktop\image.jpg) which is most likley what you want.
Also as Max points out, you should override paintComponent rather then paint:
protected void paintComponent(Graphics g){
g.drawImage(image,0,0,image.getWidth(),image.getHeight(),null);
}

Categories