how to display next image selected by file chooser next time - java

How to display next image selected by file chooser next time
This is my code that had a filechooser to choose file and display the image on jlabel.
The image is scaled to proper size correctly but when i try to choose next or other
image file through filechooser..the new image did not displayed out..previous image
stills there..not able to display the updated image..
I have also set the path name of image in the textfield and it gets set
correctly.but the image is not updated on jlabel...
please any one tell me where is
my code wrong..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser jFileChooser1 = new JFileChooser();
repaint();
jFileChooser1.setAcceptAllFileFilterUsed(false);
int state = jFileChooser1.showOpenDialog(new JFrame());
jTextField1.setText("");
jLabel1 = new JLabel();
if (state == JFileChooser.APPROVE_OPTION) {
file = jFileChooser1.getSelectedFile();
s2 = file.toString();
jTextField1.setText(s2);
jLabel1.setName(s2);
jLabel1.setLocation(40, 40);
jLabel1.setSize(300, 300);
jLabel1.setVisible(true);
try {
bi = ImageIO.read(file);
// JOptionPane.showMessageDialog(new JFrame(),file.getName());
icon = new ImageIcon(bi);
Image img = icon.getImage();
icon = new ImageIcon(file.getPath());
// icon = new ImageIcon(paths[currentIndex].getPath());
scaleImage = icon.getImage().getScaledInstance(80, 80,
Image.SCALE_DEFAULT);
resizedImage = resize(bi, 200, 200);
icon = new ImageIcon(resizedImage);
jLabel1.setIcon(icon);
jLabel2 = new JLabel();
repaint();
pack();
paths = file.getParentFile().listFiles();
currentIndex = indexOf(paths, file);
} catch (Exception e) {
System.out.println(e);
}
} else if (state == JFileChooser.CANCEL_OPTION) {
JOptionPane.showMessageDialog(new JFrame(), "Canceled");
}
add(jLabel1);
}

Don't recreate jLabel1. Store it somewhere as a field of the class and just call setIcon() passing image from the file chooser

Related

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);
}
}
});

How to load an image into a JPanel using Java

I would like to use an image as the background of a JPanel.
It needs to be loaded from a relative file path.
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JLabel background = new JLabel(new ImageIcon(backgroundImage));
this.add(background);
} catch(IOException e) {
System.out.println(e.toString());
}
}
My current code is not working. Any help would be appreciated.
So can't comment(need 50 rep) but your file path is completely wrong
you need it to be something like this
new File("C:/Users/"Insert Username"/Desktop/workspace/Java/BSC_Project/Application/src/resources/background.jpg")
except I'm not on your computer so you need to figure out your own file path, This would be assuming your workspace folder is on your Desktop which it almost certainly isn't, do you understand?
Well if you want your code to have a panel this is what you would do...
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JPanel panel = new JPanel();
JLabel background = new JLabel(new ImageIcon(backgroundImage));
panel.add(background);
this.add(panel);
} catch(IOException e) {
System.out.println(e.toString());
}
}
but in your case it looks to me like you want a frame background as image... to which you can set the image background to which for that one you can try this code
JFrame f = new JFrame ("SettingBackGround");
try{
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Med.jpg")))));
}catch (IOException e){
System.out.println("Image Doesnt Exist");
}
f.setVisible(true);
f.setResizable(false);
f.pack();
}
}
I hope this helps though.
public WelcomeView() {
initComponents();
try {
image = ImageIO.read(new File("C:\\Users\\Developer\\workspace\\Java\\BSC_Project\\Application\\src\\application\\resources\\background.png"));
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
private BufferedImage image;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 2, 0, null); // see javadoc for more info on the parameters
}

How to grab only selected components image while capturing the JPanel?

JPanel with 3 JButton and I need only two of them to be captured...
public static void grabScreenShot(JPanel panel) {
BufferedImage image = (BufferedImage) panel.createImage(
panel.getSize().width, panel.getSize().height);
panel.paint(image.getGraphics());
File file = null;
file = new File("Customers");
if (!file.exists()) {
file.mkdir();
}
try {
file = new File("Customers" + File.separator
+ String.valueOf(System.currentTimeMillis()));
ImageIO.write(image, "png", file);
System.out.println("Image was created");
} catch (IOException e) {
System.out.println("Had trouble writing the image.");
e.printStackTrace();
}
}
How to avoid unnecessary components to be captured.?
You can try to override paintComponent() of the buttons and introduce a flag needPaint. The flag is true by default.
if (needPaint) {
super.paintComponent(g);
}
In your grabScreenShot() set the flag to false for the button to be hidden and reset it back after panel.paint(image.getGraphics()); call

GWT how to make a clickhandler inside my arrayList

I have this simple ArrayList
Image img = new Image("/Mobile 005.JPG");
Image img1 = new Image("/Mobile 006.JPG");
Image img2 = new Image("/Mobile 007.JPG");
Image img3 = new Image("/Mobile 008.JPG");
imgList.add(img);
imgList.add(img1);
imgList.add(img2);
imgList.add(img3);
HorizontPanel hpnl = new HorizontalPanel();
hpnl.add(imgList);
This list of images will be coming from db and can be of any number.
At this time this HorizontalPanel contains 4 images (it may contain 400 images in future), Now if a user comes and click on the second image lets say , how will we know which image has been clicked by the user?
where and how will I put my clickHandler?
You will get to know which image is clicked by using the getSource() API as -
Image img = new Image("/Mobile 005.JPG");
img.addClickHandler( getClickHandler() );
Image img1 = new Image("/Mobile 006.JPG");
img1.addClickHandler( getClickHandler() );
Image img2 = new Image("/Mobile 007.JPG");
img2.addClickHandler( getClickHandler() );
Image img3 = new Image("/Mobile 008.JPG");
img3.addClickHandler( getClickHandler() );
imgList.add(img);
imgList.add(img1);
imgList.add(img2);
imgList.add(img3);
HorizontPanel hpnl = new HorizontalPanel();
hpnl.add(imgList);
ClickHandler imageClickHandler;
private ClickHandler getClickHandler()
{
if( imageClickHandler != null)
{
return imageClickHandler;
}
imageClickHandler = new ClickHandler()
{
public void onClick( ClickEvent event )
{
Image source = (Image)event.getSource();
// This is the source that has caused the event.
}
};
return imageClickHandler;
}
you can also try with following.
HorizontalPanel hp = new HorizontalPanel();
hp.add(getImage("/Mobile 005.JPG"));
hp.add(getImage("/Mobile 006.JPG"));
hp.add(getImage("/Mobile 007.JPG"));
hp.add(getImage("/Mobile 008.JPG"));
private Image getImage(String imagePath){
Image image = new Image(imagePath);
image.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// write the on click code.
}
});
}
From the imagepath variable, you can get to know which onclick is called.
Are looking for something like this
List<Image> images = new ArrayList<Image>();
images.add(new Image());
images.add(new Image());//Into this list add your DB images list
images.add(new Image());
for (Image image : images) {
image.addClickHandler(
//singleton instance of clickhandler
});
}

Drop File on SWT Label with Image (DND)

Problem description:
The user should be able to drag an Image-File from his computer to a RCP Application. The drop-target is a SWT-Label which is generated through the Eclipse FormToolkit. (Eclipse Forms)
With the following code, the user is able to drag Image-Files as well as Images from a Browser and drop them on the label (works well).
The problem occurs, when the label shows a image:
lblImage.setImage()
In my example, I set the image of the label, after the user dropped a file. As a consequence, subsequent drags are no longer registered.
(dragEnter method is no longer invoked)
/** create label **/
Label lblImage = fFormToolkit.createLabel(fForm.getBody(), "");
GridData gd = new GridData();
gd.widthHint = 200;
gd.heightHint = 200;
lblImage.setLayoutData(gd);
/** drag drop support **/
int ops = DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT;
final FileTransfer fTransfer = FileTransfer.getInstance();
final ImageTransfer iTransfer = ImageTransfer.getInstance();
Transfer[] transfers = new Transfer[] { fTransfer, iTransfer };
DropTarget target = new DropTarget(fLblArtWork, ops);
target.setTransfer(transfers);
target.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
if (event.data instanceof String[]) {
String[] filenames = (String[]) event.data;
if (filenames.length > 0){
Image i = new Image(Display.getCurrent(), filepath);
lblImage.setImage(i);
}
} else if (event.data instanceof ImageData) {
Image i = new Image(Display.getCurrent(), data);
lblImage.setImage(i);
}
}
public void dragEnter(DropTargetEvent event) {
System.out.println("drag enter");
event.detail = DND.DROP_COPY;
}
});
Question: How do I register dragEnter Events on a SWT Label that shows an Image?
Thanks
In your example there were some problems that caused this not to compile for me. After I fixed the issues I was able to drag png files onto the component and each successive drop changed the image correctly.
Here are the changes:
Original
DropTarget target = new DropTarget(fLblArtWork, ops);
became:
DropTarget target = new DropTarget(lblImage, ops);
Original
Image i = new Image(Display.getCurrent(), filepath);
became:
Image i = new Image(Display.getCurrent(), filenames[0]);
Original
Image i = new Image(Display.getCurrent(), data);
became
Image i = new Image(Display.getCurrent(), (ImageData) event.data);
I also create my label the following way:
final Label lblImage = new Label(shell, SWT.NONE);
but that shouldn't make a difference.
I used SashForm here to set an background image from the local system. AS per your requirement I have done the text and label also but I didn't set. You can set it by the labelobject.setImage(image);
final SashForm sashForm = new SashForm(composite, SWT.BORDER);
sashForm.setBounds(136, 10, 413, 237);
final Label lblHello = new Label(composite, SWT.NONE);
DragSource dragSource = new DragSource(lblHello, DND.DROP_NONE);
ImageTransfer imgTrans=ImageTransfer.getInstance();
FileTransfer fileTrans=FileTransfer.getInstance();
Transfer[] transfer=new Transfer[] { fileTrans,imgTrans,TextTransfer.getInstance() };
DropTarget dropTarget = new DropTarget(sashForm, DND.DROP_NONE);
dropTarget.setTransfer(transfer);
dragSource.setTransfer(transfer);
lblHello.setBounds(27, 219, 55, 15);
lblHello.setText("Hello");
dragSource.addDragListener(new DragSourceAdapter() {
#Override
public void dragStart(DragSourceEvent event) {
event.doit=true;
}
});
//Drop Event
dropTarget.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
System.out.println(event.detail);
//String path = System.getProperty("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
Image image=new Image(display, "C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
sashForm.setBackgroundImage(image);
}
});
Easy Way : Drop File on SWT Label with Image (DND)
The drop event occurs when the user releases the mouse over the Drop target.
final CLabel lblNewLabel = new CLabel(parent, SWT.BORDER);
lblNewLabel.setBounds(10, 43, 326, 241);
lblNewLabel.setText("Drop Target");
// Allow data to be copied or moved to the drop target
DropTarget dropTarget = new DropTarget(lblNewLabel, DND.DROP_MOVE| DND.DROP_COPY | DND.DROP_DEFAULT);
// Receive data in Text or File format
final TextTransfer textTransfer = TextTransfer.getInstance();
final FileTransfer fileTransfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[] {fileTransfer, textTransfer};
dropTarget.setTransfer(types);
// DropTargetEvent
dropTarget.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
if (textTransfer.isSupportedType(event.currentDataType)) {
String text = (String)event.data;
lblNewLabel.setText(text);
}
if (fileTransfer.isSupportedType(event.currentDataType)){
//clear Label Text
lblNewLabel.setText("");
//list out selected file
String[] files = (String[])event.data;
for (int i = 0; i < files.length; i++) {
String[] split = files[i].split("\\.");
String ext = split[split.length - 1];
// Set Images format "jpg" and "png"
if(ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("png"))
{
lblNewLabel.setImage(SWTResourceManager.getImage(files[i]));
}
else
{
lblNewLabel.setText(files[i]);
}
}//end for loop
}
}//End drop()
});//End addDropListener

Categories

Resources