I am using Vaadin in Java and I am following this tutorial: Vaadin Upload
So I have created a new Class name Uploader. But there is some stuff which doesn't work in my code, I put what is not working in ** text **:
import com.vaadin.server.FileResource;
import com.vaadin.ui.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by mflamant on 15/05/2017.
*/
public class Uploader {
final Embedded image = new Embedded("Uploaded image");
**image.setVisible(false);**
class Image implements Upload.Receiver, Upload.SucceededListener{
public File file;
public OutputStream receiveUpload(String filename, String mimeType){
FileOutputStream fos = null;
try{
file = new File(filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e){
e.printStackTrace();
return null;
}
return fos;
}
public void uploadSucceeded(Upload.SucceededEvent event){
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
Image receiver = new Image();
Upload upload = new Upload("Upload image here", receiver);
**upload.setButtonCaption("Start Upload");**
**upload.SucceededListener(receiver);**
Panel panel = new Panel("Image storage");
Layout panelContent = new VerticalLayout();
**panelContent.addComponents(upload, image);**
**panel.setContent;**
}
The error I have is "Can not resolve symbol". Can you explain to me why these lines aren't working?
Upload example doesn't list the whole code of the application. It only includes the code snippets specific to the Upload component itself. These code snippets are not expected to work if you just paste them into your class.
This example is a part of Vaadin Documentation and you're expected to understand the basics at the time you reach this part.
Example code is intended to work as a part of a method that builds a Vaadin component. The particular error is that you can only call methods, like image.setVisible(false) from an executable code block. You can't just paste them in your class declaration, that's not a valid Java code.
Tutorial links to a working code on Github. As you can see it contains all the necessary initialization in place:
public class UploadExample extends CustomComponent implements BookExampleBundle {
private static final long serialVersionUID = -4292553844521293140L;
public void init (String context) {
//... omitted for brevity
basic(layout);
//... omitted for brevity
}
void basic(VerticalLayout layout) {
final Image image = new Image("Uploaded Image");
//the rest of the example code goes here
Please, note that this class alone still doesn't work as a standalone application. This is just one of the components.
So, what you can do now:
Complete Vaadin Tutorial first. This should help you grasp the concepts.
Read the Introduction part of the docs first. This will help you build the working application. Then you can jump to specific components.
Clone Book Examples application from Github and then try to figure out how it works.
Related
I'm new to java.
I am trying to use Java Advanced Imaging to read an Image file as explained in here http://www.oracle.com/technetwork/java/iio-141084.html
import java.awt.image.RenderedImage;
import javax.media.jai.JAI;
public class ImageGetterJAI {
public static void main(String[] args)
{
//image source
String imagedir = "C:\\Users\\Emre\\Desktop\\Image\\Grass.tif";
//get the image
RenderedImage image = JAI.create("imageload", imagedir);
}
}
But I get JAI cannot be resolved error. Am I doing a fundamental mistake.
Screenshot of the project is below, hope this helps.
Right now I'm working on a GUI project, where I'm trying to take photos, found from the URLs I find from inside the source code of a website, and load them into my JavaFx GUI.
For example, I wish for Java to load the website http://www.imdb.com/movies-in-theaters/?ref_=nv_tp_inth_1, and collect all of the "cover photos"/thumbnails that you see as you scroll down the page (no matter the size of the image), and then load them into the GUI view (into an HBox full as a bunch of ImageViews for example).
More in-depth as well, eventually I would like to get it to the point, that the user could click on the image/imageview, and (again for example) it would show show the trailer for the selected movie. (My thinking, is that the trailer link would be found from website, if you clicked through and went to the next page, found the link, went to youtube, and removed all of the content except for the video player necessarily).
In the web-browser that I use, I have access see the page's HTML elements/design, and look through all of the source coding. After just a few twirls, I can easily find the direct URL to the thumbnail/image I'm looking for, and I've found that in javaFX I can load an image into my GUI as a URL, like so:
Image img = new Image("http://website/websiteSubPage/websiteImage");
ImageView imgView = new ImageView(img);
I've also found that the concept of what I'm looking for is called WebScraping... But all of the modules I've looked into and researched so far aren't helping with what I need. The closest module I've found so far, is HtmlUnit. However, HtmlUnit is all about web automation -- And I couldn't find anything in it's documentation on finding a photo, and loading it as a Java Image object, that is callable into an ImageView.
My best guess at the moment, is to have Java load the website in the background, gather the source code, and then I could create a String Manipulator of sorts, that would essentially just find, trim to, and load the URL of every image it finds, and put it into an HBox full of ImageViews.
Ultimately, I feel like my only solution looks something like this:
public HBox listView(){
HBox temp = new HBox();
// Load the website
// Load the source code into a large string.
for (int i=0; i>=<numberOfPhotosPreCalculatedSomeHow>;i++){
Image img = new Image( /*Manipulated string algorithm to find the next image URL*/);
ImageView imgView = new ImageView(img);
ImageView.setOnAction(e -> { /* load the trailer */ }; } // (Lambda)
temp.getChildren().add(ImageView);
}
return temp;
}
However, doing all of this... Makes me feel like I'm doing something horribly wrong, and I need some help.
Thoughts? Is there a module or plugin built specifically for this? Is this possible, or just dumb?
Found the answer!
There's built-in java methods that can allow me to scan in information from a website, and then decipher it as needed.
In my case, here's the code I used:
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class WebReader extends Application{
// Class variable to hold our found URLs :)
static ArrayList<String> listArray;
public static void main(String[] args) throws IOException {
// Gather page & URL data, and read it
String address = "http://reddit.com";
URL pageLocation = new URL(address);
Scanner in = new Scanner(pageLocation.openStream());
// Initialize an ArrayList to store all of our collected URLs
listArray = new ArrayList<String>();
// Decipher the code line by line
while (in.hasNext()) {
String line = in.next();
if (line.contains("href=\"http://")) {
int from = line.indexOf("\"");
int to = line.lastIndexOf("\"");
System.out.println(line.substring(from + 1, to));
listArray.add(line.substring(from + 1, to));
}
}
// Next, we implement into JavaFx
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("My loaded photos");
// Create a place to put our content
HBox content = new HBox();
ScrollPane scrollPane = new ScrollPane(content);
scrollPane.setFitToHeight(true);
System.out.println(listArray.size());
for (int i = 0; i <= listArray.size() - 1; i++) {
Image img = new Image(listArray.get(i));
ImageView imgView = new ImageView(img);
content.getChildren().add(imgView);
} // Launch and sail away!! :)
Scene s = new Scene(scrollPane, 800, 600);
primaryStage.setScene(s);
primaryStage.show();
}
}
So this was the solution that I was able to find-- I can't believe it took me so long to find a solution, but I hope this helps anybody who is on the same boat that I am. :)
I am learning and programming a game for android using libgdx and i have got stuck on this error for quite a long period of time. I have enclosed the following content
The code.
The command i used to access the asset.
Screenshot that contains the error when i debug the code on android.
Screenshot of my Package Explorer.
All the possible combinations i tried to get the code working.
1.The Code
package com.me.mygdxgame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.utils.Disposable;
public class Gameassetloader implements Disposable, AssetErrorListener {
public static final String TAG = Gameassetloader.class.getName();
public static Gameassetloader instance = new Gameassetloader();
private AssetManager assetManager;
/** Load the appropriate texture for the respective entities **/
public AssetCharacter boy;
public AssetRock rock;
public AssetShield shield;
/** singleton: prevent instantiation from other classes **/
private Gameassetloader(){}
public void init(AssetManager assetManager)
{
this.assetManager = assetManager;
//set asset manager error handler
assetManager.setErrorListener(this);
//load texture atlas
assetManager.load(Gameconstants.TEXTURE_ATLAS_OBJECTS,TextureAtlas.class);
//start loading assets and wait until finished
assetManager.finishLoading();
Gdx.app.debug(TAG, "# of assets loaded:" + assetManager.getAssetNames().size);
for (String a : assetManager.getAssetNames())
Gdx.app.debug(TAG, "asset:" + a);
TextureAtlas atlas = assetManager.get(Gameconstants.TEXTURE_ATLAS_OBJECTS);
//enable texture filtering for pixel smoothing
for(Texture t : atlas.getTextures())
t.setFilter(TextureFilter.Linear,TextureFilter.Linear);
//create game resource objects
boy = new AssetCharacter(atlas);
rock = new AssetRock(atlas);
shield = new AssetShield(atlas);
}
public void dispose() { assetManager.dispose(); }
#Override
public void error(String fileName, Class type, Throwable throwable)
{
Gdx.app.error(TAG, "Couldn't load asset' " + fileName + "'", (Exception)throwable);
}
}
2.The Command
public static final String TEXTURE_ATLAS_OBJECTS ="gdxgame-android/assets/packed/packed.png";
3.Screenshot of Package Explorer
http://i1294.photobucket.com/albums/b608/Abhishek_M369/PackageExplorer_zpsd2589ee2.jpg
4.Screenshot of Error log (Android DDMS)
http://i1294.photobucket.com/albums/b608/Abhishek_M369/ErrorLog_zps8a4a68d9.jpg
5.All the possible combinations i tried
"/gdxgame-android/assets/packed/packed.png";
"gdxgame-android/assets/packed/packed.png";
"/assets/packed/packed.png";
"assets/packed/packed.png";
"/packed/packed.png";
"packed/packed.png";
"/packed.png";
"packed.png";
public static FileHandle location = Gdx.files.internal("assets/packed.png");
public static final TEXTURE_ATLAS_OBJECT = location.toString();
//this caused shutdown of emulator
public static FileHandle location = Gdx.files.internal("assets/packed.png");
public static final TEXTURE_ATLAS_OBJECT = location.readString();
// I even tried setting the build path of the asset folder as source folder
// Also tried placing the image in the data folder.
// Tried using the absolute path too , i.e Gdx.files.absolute("the absolute");
// Tried passing the absolute path directly as string
Nothing seems to work for me.
The problem was very simple, the problem lied in the different versions of libgdx and the documentation. The answer explained below will solely confirm to libgdx version 0.9.8 only.
(Note: The usage of Texturepacker GUI was used to pack textures && not the method from the libgdx library)
First the "assetManager" had to be supplied with a file that contains the coordinates of the images which was a mistake here as i was supplying the packed image.
The GL20 should be able to parse NPOT images but it was unable to do so and the reason remains unknown so i had to pack the texture to a POT which was accomplished by selecting the POT options in the GUI. After doing this i was able to load the newly POT image easily with the following code
/**Mention only the folder/file under the asset dir**/
public class Gameconstants { public static final String location = "packed/packed.txt" }
/**access the same using the following command**/
private AssetManager assetManager;
assetManager.load(Gameconstants.location,Texture.class);
This Answer may not be very convincing but it surely solved my problem.
Thank you to all who helped :)
I am trying to display images inside a Browser-widget (SWT). These images can be found inside the a jar file (plug-in development). However: this is not directly possible as the browser-widget expects some kind of URL or URI information.
My idea is to turn SWT-images into data-URI values, which I could induce into the src-attribute of every given img-element. I know, that this is not a good solution from a performance point of view, but I don't mind the speed disadvantage.
I'd like to know how to turn a SWT image into a data-URI value for use in a browser-widget.
My code so far:
package editor.plugin.editors.htmlprevieweditor;
import editor.plugin.Activator;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
public class HtmlPreview extends Composite implements DisposeListener {
private final Browser content;
public HtmlPreview(final Composite parent, final int style) {
super(parent, style);
this.setLayout(new FillLayout());
content = new Browser(this, style);
final ImageData imageData = Activator.getImageDescriptor(Activator.IMAGE_ID + Activator.PREVIEW_SMALL_ID).getImageData();
content.setText("<html><body><img src=\"data:image/png;base64," + imageData + "\"/></body></html>"); // need help on changing imageData to a base64-encoded String of bytes?
this.addDisposeListener(this);
}
#Override
public void widgetDisposed(final DisposeEvent e) {
e.widget.dispose();
}
}
Any help is greatly appreciated :)!
Edit 1: I have read SWT Image to/from String , but unfortunately it does not seem to exactly cover my needs.
Edit 2: I don't know if it matters, but I am trying to load a PNG24-image with per-pixel alpha-transparency.
The question is too general if you only say "Browser in SWT". Mozzila browser supports jar URL protocol, and you can do this:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final URL url = ShellSnippet.class.getResource("/icons/full/message_error.gif");
final Browser browser = new Browser(shell, SWT.MOZILLA);
final String html = String.format("<html><head/><body>image: <img src=\"%s\"/></body></html>", url);
browser.setText(html);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
It looks like this:
I used an image from the JFace jar to keep the snippet simple and yet work for most people out of the box. It is GIF, but I expect it to work just as well with PNG files.
If you use Internet Explorer, something I do not recommend because your application depends on OS version, this does not work. It looks like this (after changing in the snippet the style from SWT.MOZILLA to SWT.NONE):
It does however understand the file protocol and you can copy files to the temp folder and create URLs directly to the file using File.toURL(). This should work for any browser.
I cannot test the simple solution on WEBKIT broswer. If anyone can, please post the result in a comment.
I created a report from my NetBeans GUI and It was working fine, but all of a sudden the compiler showing error now.
package dreportsample;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
/**
* #author Ricardo Mariaca (dynamicreports#gmail.com)
*/
public class DReportSample {
public DReportSample() {
build();
}
private void build() {
StyleBuilder boldStyle = stl.style().bold();
StyleBuilder boldCenteredStyle = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.CENTER).setFontSize(15);
StyleBuilder footerLeft = stl.style().setHorizontalAlignment
(HorizontalAlignment.LEFT) ;
StyleBuilder footerRight = stl.style().setHorizontalAlignment
(HorizontalAlignment.RIGHT) ;
//BufferedImage img = new BufferedImage(1200,1200,BufferedImage.TYPE_INT_RGB);
BufferedImage img = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
img = ImageIO.read(new File("D:/Hysteresis.png"));
} catch (IOException e) {
}
BufferedImage logo = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
logo = ImageIO.read(new File("D:/Logo.jpg"));
} catch (IOException e) {
}
try {
report()//create new report design
// .setColumnTitleStyle(boldStyle)
// .setColumnStyle(boldStyle)
.highlightDetailEvenRows()
.columns(//add columns
col.column(null,"Col_1", type.stringType()),
col.column(null,"Col_2", type.stringType())
)
.summary(
cmp.verticalList()
.add(cmp.text("\n\nHYSTERISIS PLOT").setStyle(boldStyle))
.add(cmp.text("A brief description of what this plot signifies "
+ "which means that change in are related to"
+ " pain relief and subsequently"
+ "should be encouraged \n\n\n\n"))
// .add(cmp.image(getClass().getResourceAsStream
// ("D:/Hysteresis.png")).setFixedDimension(300, 300))
.add(cmp.image(img).setFixedDimension(400, 300))
.add(cmp.text("ANALYSIS\n\n\n").setStyle(boldStyle))
.add(cmp.text("REMARKS\n\n\n\n").setStyle(boldStyle))
.add(cmp.text("Doctor Signature").setStyle(boldStyle))
)
.title(
cmp.horizontalList()
.add(
cmp.image(logo).setFixedDimension(70, 70),
cmp.verticalList()
.add(
cmp.text("Address Line 1").setStyle(boldCenteredStyle),
cmp.text("Address Line 2").setStyle(boldCenteredStyle),
cmp.text("Address Line 3").setStyle(boldCenteredStyle))
)
.newRow()
.add(cmp.filler().setStyle(stl.style().setTopBorder(stl.pen2Point())).setFixedHeight(10))
)//shows report title
// .pageFooter(cmp.pageXofY())//shows number of page at page footer
.pageFooter(
Templates.footerComponent,
//cmp.text("Emsol Software Solution \t\t\t\t\t\t\t\t"
// + " copyright: gauravbvelelx#gmail.com")
cmp.horizontalList()
.add(cmp.text("Emsol Software Solution").setStyle(footerLeft),
cmp.text("copyright: gauravbvelex#gmail.com").setStyle(footerRight))
)
.setDataSource(createDataSource())//set datasource
.show();//create and show report
} catch (DRException e) {
e.printStackTrace();
}
}
private JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("Col_1", "Col_2");
dataSource.add("Name","Sample");
dataSource.add("Age","26");
dataSource.add("Sex","Female");
dataSource.add("Weight","53 Kg");
dataSource.add("BMI","20");
dataSource.add("Massage Duration (Mins)","4.5");
dataSource.add("RPM","26");
dataSource.add("Doctor Attended","Doctor");
dataSource.add("Date","22-Feb-2013");
return dataSource;
}
public static void main(String[] args) {
new DReportSample();
}
}
This code worked fine just few hours back. But now it is suddenly showing error:
Screen shot attached
Same kind of error it is showing at report() and other parts as well. Basically it is not able to recognize various classes and fields of dynamic reports library though the library has been imported successfully, though few hours back it was working well.
The way I am using dynamic reports is by adding the libraries as below:
1) Downloaded dynamicreports-3.1.0-project-with-dependencies
2) Unzipped
3) In my Netbeans Project
Libraries -> Add Jar/folder -> Selecting all files from dynamicreports-3.1.0-project-with-dependencies\dynamicreports-3.1.0\lib
Libraries -> Add Jar/folder -> Selecting all files from dynamicreports-3.1.0-project-with-dependencies\dynamicreports-3.1.0\dist
It worked fine, but then then I changed the name of the folder where I saved dynamicreports-3.1.0-project-with-dependencies, due to which It gave me Reference Error for added libraries. So I again rechanged it to previous name, but since then I am getting the error shown.
I have tried everything, building new project and following the steps mentioned or re downloading new dynamicreports-3.1.0-project-with-dependencies and again following the steps. But nothing seems to work, its frustrating as I was so close to complete my project.
Can anyone help please.
Thanks
Ok.. resolved it..
Below line got deleted causing the errors:
import static net.sf.dynamicreports.report.builder.DynamicReports.*;