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
});
}
Related
I am trying to get the images (blob) from DB and adding it to a tableview JavaFX
But the quality is drastically reducing, even color is inverted. Any solution for this?
My code :
Main Form
for (StudentDTO s : studentDTOS) {
ImageView img = ImageController.blobToImage(s.getImage());
Button btn = new Button("Edit");
tmList.add(new ReceptionistStudentTM(
s.getId(),
img,
s.getName(),
s.getEmail(),
s.getNic(),
s.getScholaMark(),
s.isStatus(),
btn
));
}
tblStudents.setItems(tmList);
ImageController.java
public class ImageController {
public static ImageView blobToImage(Blob blob) throws SQLException {
return new ImageView(new Image(blob.getBinaryStream()));
}
}
Thanks for your time
I tested this code in order to create dialog with image.
final int xSize = 400;
final int ySize = 280;
final Color backgroundColor = Color.WHITE;
final String text = "SQL Browser";
final String version = "Product Version: 1.0";
final Stage aboutDialog = new Stage();
aboutDialog.initModality(Modality.WINDOW_MODAL);
Button closeButton = new Button("Close");
closeButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
aboutDialog.close();
}
});
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Image img = new Image("logo.png");
ImageView imgView = new ImageView(img);
grid.add(imgView, 0, 0);
grid.add(new Text(text), 0, 1);
grid.add(new Text(version), 0, 2);
grid.add(closeButton, 14, 18);
Scene aboutDialogScene = new Scene(grid, xSize, ySize, backgroundColor);
aboutDialog.setScene(aboutDialogScene);
aboutDialog.show();
I placed the image file into the directory /src.
But for some reason the image is not displayed. Can you help me to correct my mistake?
Simply replace this code:
Image img = new Image("logo.png");
with this
Image img = new Image("file:logo.png");
Docu reference.
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/Image.html
When you pass a String to the Image class it can be handled in four different ways (copied from docu):
// The image is located in default package of the classpath
Image image1 = new Image("/flower.png");
// The image is located in my.res package of the classpath
Image image2 = new Image("my/res/flower.png");
// The image is downloaded from the supplied URL through http protocol
Image image3 = new Image("http://sample.com/res/flower.png");
// The image is located in the current working directory
Image image4 = new Image("file:flower.png");
The file: prefix is simply an URI scheme, or in other words the counterpart to the http: protocol classifier. This also works in the file browser, or in the web browser... ;)
For further reference, you can take a look at the wiki page of the file URI scheme: https://en.wikipedia.org/wiki/File_URI_scheme
Happy Coding,
Kalasch
Try this:
img = new Image("/logo.png");
If no protocol part indicating a URL (as http: or file:) is given, the file is supposed to reside in the default package. If you want it to put in a different package say com.my.images you add this information in a path like manner:
img = new Image("/com/my/images/logo.png");
Image img = new Image("file:/logo.png");
or way with path:
Image img = new Image("file:c:/logo.png");
or
File f = new File("c:\\logo.png");
Image img = new Image(f.toURI().toString());
also can use:
new Image(file:src/logo.png) //root of project
This functions:
Image image = new Image(getClass()
.getResourceAsStream("ChimpHumanHand.jpg"));
copy and paste the image into folder where source package(source packages in NetBeans IDE) is present. Then
Image image = new Image("a1.jpg");
Image image = new Image("File:a1.jpg");
both will work.
I am using GWT FileUpload() and a form to let the user select an image and upload it to the server. What I want to do is preview the image before it gets to the server. I am only able to get the file name from the FileUpload()
HorizontalPanel row = new HorizontalPanel();
row.add(accounts = new ListBox());
accounts.setWidth("200px");
row.setStyleName("accountPositioning");
accounts.setName("accounts");
final Image image = new Image();
image.setStyleName("previewImage");
setCellSpacing(10);
panel = new VerticalPanel();
panel.add(row);
panel.add(image);
final FormPanel form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
downloadPanel = new FormPanel();
downloadPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
downloadPanel.setMethod(FormPanel.METHOD_GET);
deletePanel = new FormPanel();
deletePanel.setEncoding(FormPanel.ENCODING_MULTIPART);
deletePanel.setMethod(FormPanel.METHOD_POST);
upload = new FileUpload();
upload.setName("upload");
upload.setStyleName("chooseImageButton");
upload.setEnabled(false);
upload.setVisible(false);
VerticalPanel holder = new VerticalPanel();
uploadButton = new Button("Import");
uploadButton.setEnabled(false);
uploadButton.setStyleName("importImageButton");
uploadButton.setVisible(false);
uploadButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
String filename = upload.getFilename();
if (filename.length() == 0) {
Window.alert("No File Specified!");
} else {
int selectedIndex = accounts.getSelectedIndex();
accountIdStr = accounts.getValue(selectedIndex);
form.setAction(GWT.getModuleBaseURL()+"uploadfile" + "?entityId="+ accountIdStr);
form.submit();
}
}
});
How can i get the file path of the image file upload using GWT FileUpload() so i can preview the image before submitting it to the server?
I am using GWT 2.7.0 version so i cant use File, or Path library
You're going to need to get the File object out of the element...
And you can do it like this:
#Override
public elemental.html.FileList fileSelected(FileUpload fileUpload) {
final elemental.html.InputElement element = (elemental.html.InputElement) fileUpload.getElement();
return element.getFiles();
}
As you can see it uses gwt elemental.
Once you've extracted the File object you can do this:
import com.google.gwt.user.client.Element;
import elemental.html.File;
import elemental.html.ImageElement;
import elemental2.dom.FileReader;
public void loadPreview(File file) {
FileReader reader = new FileReader();
reader.onloadend = pe -> {
Element element0 = this.image.getElement();
com.google.gwt.dom.client.Element element = element0;
ImageElement image = (ImageElement) element;
image.setSrc(reader.result.asString());
image.addEventListener("load", evt -> {
LOG.debug("image loaded event {}", evt);
int owidth = image.getWidth();
int oheight = image.getHeight();
LOG.debug("widht {}', height {}", owidth, oheight);
//IMAGE_VIEW_PORT_WIDTH
//IMAGE_VIEW_PORT_HEIGHT
int height;
int width;
if (owidth >= (destAspectRatio) * oheight) {
height = (int) Math.round(IMAGE_VIEW_PORT_WIDTH * (oheight / (double) owidth));
width = IMAGE_VIEW_PORT_WIDTH;
} else {
width = (int) Math.round(IMAGE_VIEW_PORT_HEIGHT * (owidth / (double) oheight));
height = IMAGE_VIEW_PORT_HEIGHT;
}
image.setWidth(width);
image.setHeight(height);
this.image.setVisible(true);
LOG.debug("new width {}, new height {}", width, height);
});
return null;
};
reader.readAsDataURL((elemental2.dom.File) file);
}
I'm sorry it's so complex - it the code that I have and I think it figures out the correct view port size so that image is set to the correct size (though I'm not 100% sure).
You might get way without the image.addEventListener("load"...) handler as I believe it's the image.setSrc(reader.result.asString()) that is the money bit.
It's using a lot of elemental and elemental2 as stock gwt just doesn't give you enough exposure to the actual API you're dealing with.
Notice also that this uses the File object from elemental.
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
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