Alright I am super confused right now, I am using a piece of code in my program that is 95% similar to another piece I've used in an another program, the only difference is that it worked in the previous program...
it is basically a Image loading class/method and I'm trying to call it in my main class but its not working and the "cannot find symbol - class Image" error occurs.
Where I'm calling the method from my GameImage class:
//STORE IMAGES
private static Image background;
GameImage class:
public class GameImage
{
public static Image loadImage(String imagePathName) {
// All images are loades as "icons"
ImageIcon i = null;
// Try to load the image
File f = new File(imagePathName);
if(f.exists()) { // Success. Assign the image to the "icon"
i = new ImageIcon(imagePathName);
}
else { // Oops! Something is wrong.
System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");
System.exit(0);
}
// Done. Either return the image or "null"
return i.getImage();
} // End of loadImages method
}
Where I load the image in main class:
//load the images
background = GameImage.loadImage("Images//background.jpg");
So yeah I dont know why that error keeps popping up because ive used that exact same code structure and GameImage class in another program... hmm
Any help would be great thanks :)
You lack the Image import statement.
Import the Image class and you should be fine.
Related
I have tried so many way but i can't succeed. I haven't found any source code examples for Android(about rekognition)
there's a source code in JAVA in the Developer Guide but i cannot implement that even though I tried TT
I try to detect faces by sending an image file from an external storage(from the emulator)
I don't know what i did wrong(I'm not good at coding)
Here is my code
AmazonRekognitionClient amazonRekognitionClient;
Image getAmazonRekognitionImage;
DetectFacesRequest detectFaceRequest;
DetectFacesResult detectFaceResult;
File file = new File(Environment.getExternalStorageDirectory(),"sungyeol.jpg.jpg");
public void test_00(View view) {
ByteBuffer imageBytes;
try{
InputStream inputStream = new FileInputStream(file.getAbsolutePath().toString());
imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
Log.e("InputStream: ",""+inputStream);
Log.e("imageBytes: ","");
getAmazonRekognitionImage.withBytes(imageBytes);
// Initialize the Amazon Cognito credentials provider
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-east-2:.......", // Identity Pool ID
Regions.US_EAST_2 // Region
);
//I want "ALL" attributes
amazonRekognitionClient = new AmazonRekognitionClient(credentialsProvider);
detectFaceRequest = new DetectFacesRequest()
.withAttributes(Attribute.ALL.toString())
.withImage(getAmazonRekognitionImage);
detectFaceResult = amazonRekognitionClient.detectFaces(detectFaceRequest);
detectFaceResult.getFaceDetails();
}
catch(Exception ex){
Log.e("Error on something:","Message:"+ex.getMessage());
}
and here is my errors
02-04 09:30:07.268 29405-29405/? E/InputStream:: java.io.FileInputStream#a9b23e7
02-04 09:30:07.271 29405-29405/? E/Error on something:: Message:Attempt to invoke virtual method 'com.amazonaws.services.rekognition.model.Image com.amazonaws.services.rekognition.model.Image.withBytes(java.nio.ByteBuffer)' on a null object reference
what is a null object reference?
i try to change the file path but he said no such file ... and when I change to this path, there's errors above.
by the way I've already asked a user for a permission to access a folder from Emulator in Android
please help me
PS. sorry for my bad English
Thank you in advance.
Now I am ok with the issues. I have been through many many things <3 <3 <3.
Thank you
I'm Thai and I had to try harder to find the solutions because there's lack of information in the particular language. Here are my solutions.
My solutions are:
0.There is an endpoint for setting for the Rekognition-->
http://docs.aws.amazon.com/general/latest/gr/rande.html#rekognition_region
1.On a "null object reference issue" I found that I have to create a new object first such as "Image image = new Image();" <-- The "new" command creates an object instance in that class
2.After the above error, there are more errors (Errors on NetworkOnMainThreadException), so I tried everything until I found this page -->
https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html the page said that ...
Consequently, I looked up for more information about the AsyncTask and after that I created an AsyncTask class and then I move all my code about the initialize, the request, the response to the AsyncTask class. ตอนรันตอนท้ายๆน้ำตาจิไหล my code worked... TT and by the conclusion the sungyeol.jpg.jpg file worked
for example
private void testTask(){
.... all code in the main thread particularly on the requests and responses
from the services
//print the response or the result
//Log.e() makes the message in the android monitor red like an error
Log.e("Response:", [responseparameter.toString()]);
}
//create the inherited class from the AsyncTask Class
//(you can create within your activity class)
class AsyncTaskRunner extends AsyncTask<String,String,String>{
#Override
public String doInBackground(String ... input){
testTask(); // call the testTask() method that i have created
return null; // this override method must return String
}
}
//I've created a button for running the task
public void buttonTask(View view){
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
for more information about the AsyncTask:
https://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask
http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.WJdkqVOLTIU
I hope these help :)
everybody.
I am novice in Java and making training project with UI.
In process of trainings I decided to load icons from resources and to move its loading in the different class.
And got problem.
I really tried to find answers by myself but could not.Code bellow.
Main class
package scv.paul;
…
/**
* Create the application.
*/
public TestApp() {
Logger.getLogger(loggerName).fine("Showing main window");
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Test App");
**frame.setIconImage( MyImages.appIcn.getImage());**//here try to load icon
And get exception:
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
Utility class
package scv.paul;*
import javax.swing.ImageIcon;
public class MyImages {
public static final ImageIcon appIcn = new ImageIcon ( MyImages.class.getResource ( "AppIcon.png" ) );
public static final ImageIcon BtnIcn = new ImageIcon ( MyImages.class.getResource ( "OK.png" ) );
public static final ImageIcon exitIcn = new ImageIcon ( MyImages.class.getResource ( "door.png" ) );
}
Images lay in "\bin" folder
I understand that the problem in the initialization of the static fields. But can’t understand reason.
I got this error if I call even such static field
public static final String imgPath = System.getProperties().getProperty("user.dir")+"\\img\\";
But I have no errors if I call in main class this static field
public static final String imgPath = "c://myProjectPath//bin";
And I could not find how to work with resources in good stile. Where I could read it?
Don't use static variables for something like this. There is no need to keep a reference to the icon. Just read the Icon and add it to your button.
Just load the images in the constructor of your class (when you create your buttons). See the section from the Swing tutorial on How to Use Icons for more information and working examples.
The tutorial will also show you how to better structure your code so the Swing components are created on the Event Dispatch Thread.
Keep a link to the tutorial handy for other Swing basics.
Put you images in the directory of the projecet, e.g. where the bin and src folders are located.
Its best to use a static method to read in files aswell incase they fail. Say you your resource folder within the directory called resources, your code would look something like this.
public static ImageIcon makeImageIcon(String filename) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("resources/" + filename));
} catch (IOException e) {
e.printStackTrace();
}
return new ImageIcon(myPicture);
}
And then call this with the file name you want the same way you have done above.
public static ImageIcon image= makeImageIcon("myImage.png");
Hope this helps.
I am working by way through a tutorial: http://www.kilobolt.com/day-4-enter-the-robot.html
and have been having a problem getting a simple image to display in the applet. I am using IntelliJ 13 Community Edition. The main for loading the images is here:
It does the image setup in the init method:
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("Q-Bot Alpha");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
// Image Setups
character = getImage(base, "data/character.png").toString());
}
where character is a sprite I obtained from the tutorial website. I saved it in a folder called data. The file structure can be seen here:
When I run this I just see a black background and character.png is not displayed. However if I change the getImage line to:
character = getImage(base, new URL("http://www.kilobolt.com/uploads/1/2/5/7/12571940/character.png").toString());
and point at the URL directly it works. I suspect this must be a path issue but I have not been able to get it working.
I am working on the same program and had the same problem. When run, the document base is actually in KiloboltGame/bin so you need to add your data/character.png here.
I want to call the return statement tempimage in load_picture by passing it to showWindow, but I'm not sure how. heres a snippet of my code. edit:
i guess what I'm trying to say is, I'm not exactly sure what to do with the hardcoded "picture1.gif". I understand that I need to call a method to load the image, but I'm not too sure what to put in place of it.
:
package project3;
import java.util.Scanner;
import javax.swing.;
import java.awt.;
import java.net.*;
public class Project3 {
//initializing global
static Project3 theobject = new Project3();
final static int MIN_NUMBER=1;
final static int MAX_NUMBER=8;
static int image_number=1;
static Image theimage;
// This routine will load an image into memory, non-static requires an object
// It expects the name of the image file name and a JFrame passed to it
// It will assume an Internet conection is available
// It can only be called AFTER the program object has been created
// It will return a type Image variable, call it like this: theimage = object.load_picture("picture1.gif", frame);
// (hard code 'picture1.gif' only when testing - USE a method or variable for 'real' call)
// This code requires you to do an 'import java.awt.*' and an 'import java.net.*'
// Note: this method is using parameter and return type for input/output
// This routine will load an image into memory, non-static requires an object
// It expects the name of the image file name and a JFrame passed to it
// It will assume an Internet conection is available
// It can only be called AFTER the program object has been created
// It will return a type Image variable, call it like this: theimage = object.load_picture("picture1.gif", frame);
// (hard code 'picture1.gif' only when testing - USE a method or variable for 'real' call)
// This code requires you to do an 'import java.awt.*' and an 'import java.net.*'
// Note: this method is using parameter and return type for input/output
public Image load_picture(String imagefile, JFrame theframe)
{
Image tempimage;
// Create a MediaTracker to inform us when the image has
// been completely loaded.
MediaTracker tracker;
tracker = new MediaTracker(theframe);
// getImage() returns immediately. The image is not
// actually loaded until it is first used. We use a
// MediaTracker to make sure the image is loaded
// before we try to display it.
String startURL;
if (imagefile.startsWith("http"))
startURL = "";
else
startURL = "http://www.canyons.edu/departments/comp_sci/ferguson/cs111/images/";
URL myURL=null;
try
{
myURL = new URL(startURL + imagefile);
}
catch(MalformedURLException e) {
System.out.println("Error caught " + e.toString());
}
//tempimage = getImage(myURL); // JApplet version
tempimage = Toolkit.getDefaultToolkit().getImage(myURL); // stand alone program version
// Add the image to the MediaTracker so that we can wait for it
tracker.addImage(tempimage, 0);
try { tracker.waitForID(0); }
catch ( InterruptedException err) { System.err.println(err); }
return tempimage;
}
// This class/method uses a global variable that MUST be set before calling/using
// note: You can not call the paint routine directly, it is called when frame/window is shown
// look up the repaint() routine in the book
// Review Listings 8.5 and 8.6
//
public static class MyPanel extends JPanel {
public void paintComponent (Graphics g) {
JPanel panel= new JPanel();
int xpos,ypos;
super.paintComponent(g);
// set the xpos and ypos before you display the image
xpos = 300; // you pick the position
ypos = 200; // you pick the position
if (theimage != null) {
g.drawImage(theimage,xpos,ypos,this);
// note: theimage global variable must be set BEFORE paint is called
}
}
}
public static void showWindow( String filename ) {
// create, size and show a GUI window frame, you may need to click on taskbar to see window
//display the filename in the title of the window frame, otherwise the window will be blank (for now)
JFrame frame1= new JFrame();
theimage = theobject.load_picture("picture1.gif", frame1);
//"picture1.gif" is hardcoded, I want to call this using a method
frame1.setTitle(filename);
frame1.setSize(440,302);
frame1.setLocation(400,302);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
Any help is appreciated. Thanks
The value that is returned by the load_picture method can be sent directly to the showWindow method, or you can assign it to a variable:
String filename = "your/filename";
JFrame theFrame = new JFrame();
Project3 project = new Project3();
MyPanel.showWindow(project.load_picture(filename, theFrame);
From within the showWindow method, just call the load_picture method as follows:
Image tempImage = load_picture(filename, frame1);
From here you can do anything you like with the tempImage object.
Is it possible to use Java to get a screenshot of an application external to Java, say VLC/Windows Media Player, store it as an Image object and then display it in a JLabel or something of a similar nature? Does anybody know if this is possible and if so does anybody have a general idea as to how to do it?
Note: I just need to find out how to get a screenshot and store it as some form of Image object. After that I can use, manipulate it, display it, etc.
Here is the answer for Windows (not sure if alt+printScr works on linux :P)
I guess one way to achieve this
1. using Robot class to fire alt+printScreen Command (this captures active window to clipboard)
2. read the clipboard!
Here are the two pieces of code that do that. I have not actually tried, but something that I pieced together.
Code to Fire commands to get active window on clipboard
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class ActiveWindowScreenShot
{
/**
* Main method
*
* #param args (not used)
*/
public static void main(String[] args)
{
Robot robot;
try {
robot = new Robot();
} catch (AWTException e) {
throw new IllegalArgumentException("No robot");
}
// Press Alt + PrintScreen
// (Windows shortcut to take a screen shot of the active window)
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_ALT);
System.out.println("Image copied.");
}
}
Code to read image on clipboard
// If an image is on the system clipboard, this method returns it;
// otherwise it returns null.
public static Image getClipboard() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
You can manage the control as you need to! Let me know if this works for you. but this is certainly on my todo to try it out!
You can get screen shot of whole screen using class named Robot. Unfortunately you cannot get location and size of windows that belong to other applications using pure java solution. To do this you need other tools (scripting, JNI, JNA). These tools are not cross-platform.