I used some of the information around this site to find out to use URLs to get images into a jar file; which I want to be able to be used alone. But when I make the jar file with BlueJ, only some images show up.
Its a blackjack game, and only the table canvas shows up, while no cards ever do. Here's the code:
THIS WORKS (the table):
public class TableComponent extends JLabel{
BufferedImage table;
public TableComponent(){
URL finalTable = getClass().getResource("blackjackTableCanvas.jpg");
try {
table = ImageIO.read(finalTable);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(table, 0, 0, null);
}...}
but this does not (the cards):
public class CardRender2 extends JComponent{
BufferedImage image;
String val;
String suit;
String filename;
public CardRender2(Card card) {
this.val = card.value.face;
this.suit = card.suit.toString();
filename = this.fetchCardFileLabel();
URL cardview = getClass().getResource("\\card deck\\" + filename + ".png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
public CardRender2(){
this.val = null;
this.suit = null;
filename = "DEALER_FIRST_CARD";
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(image, 0, 0, null);
}...}
my cards are in a folder in the directory I try to import into BlueJ, whereas the table is in the directory root. There are 53 cards in there (incl dealer hidden card) and I'd rather not put all of then in the root. I tried to implement them similarly. How can I do this?
looks like changing from
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
to
URL cardview = getClass().getResource("card deck/DEALER_FIRST_CARD.png");
did the trick.
Related
I'm learning Java, and I've converted File type into Image using IOException, but how can I use my new Image outside of try/catch?
try {
File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
Image image = ImageIO.read(obraz);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image);
}
Because now IntelliJ does not recognize image.
In this case - as paintComponent will be called often, and you want to load the image just once, put the image in a field.
private Image image;
...() {
try {
File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
image = ImageIO.read(obraz);
} catch (IOException ex) {
ex.printStackTrace();
}
}
...() throws IOException {
File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
image = ImageIO.read(obraz);
}
#Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
if (image != null) {
g2.drawImage(image);
}
}
I have shown two solutions:
catching the exception as done now: but one should do something, give an error message to the user that file logo.jpg does not exist
passing the exception on by throws, often the better solution.
The convention is to use #Override as this catches typos like public void paintComponent(Graphics2D g) or public void painComponent(Graphics g).
Im coding a liitle game for java and want to make the Player look like a rocket, so i try to load the miage and then draw it on Java awt canvas.
Unfortunately i kepp gettin an IOException, but i dont get why... is the image some how wrong?
Thank you ver helpiNg me in advance and here`s the code:
(the image is in the same package as the Player class)
public class Player extends GameEntity {
private BufferedImage img;
public Player(int x, int y, ID id){
super(x, y , id);
}
BufferedImage loadImage(String fileName) {
BufferedImage bi = null;
//System.err.println("....setimg...." + fileName);
try {
bi = ImageIO.read(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
System.out.println("Image could not be read");
System.exit(1);
}
return bi;
}
#Override
public void tick() {
x += velX;
y += velY;
}
#Override
public void render(Graphics graphics) {
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
BufferedImage rocketImage = loadImage("rocket.png");
Graphics2D g2d = (Graphics2D) graphics;
g2d.drawImage(rocketImage, at, null);
}
}
I am trying to load a spritesheet, but it is not working. It gives an error Exception in thread "Thread-0" java.lang.IllegalArgumentException: input == null!
I saved the image into folders } res --> Textures --> sheets.png . I made sure the res folder is in the Class Folder by building a path.
Please help
// public class Game
private void init(){
display = new Display(title, width, height);
test = BufferedImageLoader.loadImage("/sheets.png");
Assets.init();
}
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
g.clearRect(0, 0, width, height);
g.drawImage(test, x, 10, null);
//End Drawing!
bs.show();
g.dispose();
}
// public class BufferedImageLoader {
public static BufferedImage loadImage(String path){
try {
return ImageIO.read(BufferedImageLoader.class.getClassLoader().getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
}
Figured it out! Make a separate folder with all the images in the source folder. Then, use the link /folder name/ photo name . format (ex. "/Images/mario.png"). This way works.
I want to send a Image object over a network in java.
Im getting this error.
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: sun.awt.image.OffScreenImage
The java Image object doesn't implement Serializable. Is there a way to get around this?
Ive already tried making a subclass of image and implement it but Then I got errors when using the createImage method. Thanks for any help.
EDIT*
Ok here is the code but there is kinda a lot. The idea of the program is for it to be a pictionary game. Someone can draw using basic tools and it will send it over a network and draw that image on other clients screen.
This is my basic draw area where the user and draw using a line tool. On mouse Released it will try and send the Image object over to the server.
class PadDraw extends JComponent {
Image image;
Graphics2D graphics2D;
int currentX, currentY, oldX, oldY;
int lineSize = 1;
public PadDraw() {
setDoubleBuffered(false);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
//graphics2D.drawLine(oldX, oldY, currentX, currentY); //this is where it does the drawing
//It seems to draw a line between the old coordinate point and the new coordinate point rather than drawing it as points
//Test to see if I can get a drawoval to work rather than a line
//graphics2D.fillOval(currentX-1, currentY-1, 2, 2);
//if this works it should draw an oval at the cursor position rather than drawing a line
//technically it works, but without a line it causes gaps
//I may have found it. Testing the setStroke method
graphics2D.setStroke(new BasicStroke(lineSize));
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
try {
clientOutputStream.writeObject(image);
} catch (IOException ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
#Override
public void paintComponent(Graphics g) {
if (image == null) {
image = (Image) createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D) image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
public void updateImage(Image image){
this.image = image;
repaint();
}
public void clear() {
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
//graphics2D.setPaint(Color.BLACK);
lineSize = 1;
repaint();
}
public void fill(){
Color c = findColor();
graphics2D.setPaint(c);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
repaint();
}
public void changeColor(Color theColor) {
graphics2D.setPaint(theColor);
repaint();
}
public Color findColor() {
return graphics2D.getColor();
}
public void changeSize(int size) {
lineSize = size;
}
}
This is my threaded class for the image on the server.
private static class Handler2 extends Thread {
private Socket socket1;
private ObjectInputStream serverInputStream;
private ObjectOutputStream serverOutputStream;
public Handler2(Socket sock1) {
socket1 = sock1;
}
#Override
public void run() {
Image image = null;
try {
serverInputStream = new ObjectInputStream(socket1.getInputStream());
serverOutputStream = new ObjectOutputStream(socket1.getOutputStream());
oos.add(serverOutputStream);
while (true) {
image = (Image)serverInputStream.readObject();
for (ObjectOutputStream ooss : oos) {
ooss.writeObject(image);
}
}
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (serverOutputStream != null) {
oos.remove(serverOutputStream);
}
try {
socket1.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
And back in the client I have a method for getting the image back from the server.
public void run2() throws IOException, ClassNotFoundException, InterruptedException {
// Make connection and initialize streams
serverAddress = getServerAddress();
Socket socket2 = new Socket(serverAddress, 9999);
//String theIP = getIP();
//Socket socket2 = new Socket(theIP, 9999);
// Process all messages from server, according to the protocol.
clientOutputStream = new ObjectOutputStream(socket2.getOutputStream());
clientInputStream = new ObjectInputStream(socket2.getInputStream());
while (true) {
Image ni = (Image)clientInputStream.readObject();
drawPad.updateImage(ni);
}
}
I know my code is kinda bad. I split thinks up a lot to test individual parts. As fare as the network code. It should work. The only problem I believe is that its not serializable.
The java Image object doesn't implement Serializable. Is there a way to get around this?
You can Serialize it yourself. You can wrap it with a class which is Externalizable, or you can write the data in the image without using writeObject.
Simple answer: no. sun.awt.image.OffScreenImage is not meant to be directly serialized so you can't just add the Serializable interface on a child class to make it serializable.
You have to find a work around, I'm not sure what is this image about but, for example, if it's from a set of known images then you can just send a key to it over the network so that you can recover it on the otherside. If you need to pass directly the image data then you'll have to encapsulate it in another object and rebuild the OffScreenImage on the other side.
You can extend the class and make it serializable with some work but since it seems to be a class tighly coupled with the operating system it will need some thinking.
How to crop images in Java? I currently have this class for image manipulation.
The main method with the run method:
public static void main(String[] args) {
GameProject gp = new GameProject();
gp.run();
}
public void run(){
s = new Screen();
try {
DisplayMode dm = s.findFirstCompatibleMode(modes);
s.setFullscreen(dm);
Fonts f = new Fonts(); //Checks if certain fonts exsist, if not install them.
Images i = new Images();
try {
i.draw("H:\\Dropbox\\Dropbox\\GameProject\\src\\Resources\\brock.png", 200, 200);
Thread.sleep(50000);
} catch (Exception e) {}
} finally {
s.restoreScreen();
}
}
Images class:
package Handlers;
import javax.swing.ImageIcon;
import java.awt.*;
/**
*
* #author Steven
*/
public class Images {
/**
* #param args the command line arguments
*/
private Screen s;
public void draw(String name, int x, int y) { //Draws the image
s = new Screen();
Graphics2D g = s.getGraphics();
draws(g, name, x, y, getWidth(name), getHeight(name));
}
public void drawA(String name, int x, int y){ //Draws the image, allows for a more advanced image manipulation
s = new Screen();
Graphics2D g = s.getGraphics();
draws(g, name, x, y, getWidth(name), getHeight(name));
}
public void draws(Graphics g, String name, int x, int y, int w, int h) { //Draws and updates the screen
s = new Screen();
g.drawImage(new ImageIcon(name).getImage(), x, y, w, h, null);
s.update();
}
public int getWidth(String name) { //Gets the image width
return new ImageIcon(name).getIconWidth();
}
public int getHeight(String name) { //Gets the images height
return new ImageIcon(name).getIconHeight();
}
}
Any help would be appreciated.
You can use CropImageFilter to crop images. Also, take a look at the java.awt.image package, it does have a lot of image manipulation routines.
I have used this in my own project :-
public boolean CropImage(int cropHeight,int cropWidth,int windowLeft,int windowTop,File srcFile,String destDirectory,String destFilename,int commonPadding,String fileFormat,HttpServletRequest request)throws IOException{
boolean isOkResolution=false;
try {
String dirPath=request.getRealPath("")+"/"+destDirectory;
File f=new File(dirPath);
if(!f.isDirectory()){
f.mkdir();
}
String destpath=dirPath+"/"+destFilename;
File outputFile=new File(destpath);
FileInputStream fis=new FileInputStream(srcFile);
BufferedImage bimage=ImageIO.read(fis);
System.out.println("Image Origilnal Height=="+bimage.getHeight());
BufferedImage oneimg=new BufferedImage(cropHeight,cropWidth,bimage.getType());
Graphics2D gr2d=oneimg.createGraphics();
isOkResolution=gr2d.drawImage(bimage,0,0,cropWidth,cropHeight,windowLeft-commonPadding,windowTop-commonPadding,(windowLeft+cropWidth)-commonPadding,(windowTop+cropHeight)-commonPadding,null);
gr2d.dispose();
ImageIO.write(oneimg,fileFormat,outputFile);
} catch (FileNotFoundException fe) {
System.out.println("No File Found =="+fe);
} catch(Exception ex){
System.out.println("Error in Croping File="+ex);
ex.printStackTrace();
}
return isOkResolution;
}
This method will help you to crop the image.Its working fine for my project.Hope it will help you out.