Monday 28 May 2012

Upload an image in swings


package basic;

import java.io.*;

import javax.swing.*;

import java.awt.Button;
import java.awt.Label;
import java.awt.event.*;

public class JLabelUploadImage {
static File file;
static JFrame frame;
private static JLabel label1;
static ImageIcon icon;


public static void main(String[] args) {
// final JPanel panel = new JPanel();
frame = new JFrame("Upload Image");
frame.setLayout(null);
label1 = new JLabel();

label1.setBounds(300, 300, 300, 100);
frame.add(label1);

final JFileChooser fc = new JFileChooser();
Button browse = new Button("Browse File");
browse.setBounds(200, 300, 40, 30);
frame.add(browse);
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
System.out.println(file.getName());
}
}
});
Button button = new Button("Upload Image");
button.setBounds(100, 300, 40, 30);
frame.add(button);

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {
System.out.println("upload");
String path = file.getAbsolutePath();
System.out.println(path);
icon = new ImageIcon(path);
label1.setIcon(icon);
frame.add(label1);

System.out.println(icon.getIconHeight());

}

});
frame.add(browse);
frame.add(button);
frame.setSize(700, 700);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

No comments:

Post a Comment