I have created a simple graphics program(LIKE VERY SIMPLE). It worked all fine when I ran the class file, but when I simply created a JAR file (executable), nothing ran. Could I please get a bit of help with this. Thanks. I compiled it normally in the cmd, with the command "jar -cf Graphics.jar Graphics.class Render.class icon.png"
Graphics.java:
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Graphics extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public Graphics() {
JFrame window = new JFrame();
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setSize(500, 500);
window.add(new Render());
window.setTitle("Example of Graphics in JAVA");
ClassLoader ldr = this.getClass().getClassLoader();
URL imager = ldr.getResource("./icon.png");
String path = imager.getPath();
File f = new File(path);
File imageicon = f;
Image im = null;
try {
im = ImageIO.read(imageicon);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
window.setIconImage(im);
window.setVisible(true);
}
public static void main(String[] args) {
Graphics g = new Graphics();
}
}
Render.java:
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
public class Render extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics graph) {
super.paintComponent(graph);
this.setBackground(Color.blue);
graph.setColor(Color.red);
graph.fillArc(0,0, 400, 400, 0, 360);
}
}
There is also an image called "icon.png"
Change the File:
im = ImageIO.read(imageicon);
Back to the URL:
im = ImageIO.read(imager);
As an embedded resource (in the Jar) it is no longer a File.
Related
I'm trying to make a 2d side scrolling game. I have been able to display the background but as soon as I add a sprite the only thing displayed on the frame is the sprite. (Sorry if this is a simple mistake but I am new to java)
Here is my main class
package com.projectelrond.main;
import javax.swing.JFrame;
import com.projectelrond.Sprites.Ranger;
public class Main {
public int WIDTH = 160, HEIGHT = WIDTH/12 *9, SCALE = 3;
public boolean running = false;
BackGround bg = new BackGround();
JFrame f = new JFrame("name");
public static void main(String[] args) {
new Main();
}
public Main() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(WIDTH * SCALE, HEIGHT * SCALE);
f.setResizable(false);
f.add(new BackGround());
f.add(new Ranger());
f.setVisible(true);
running = true;
run();
}
public void run() {
while (running) {
//handles in game events NPCs, Traps etc.
}
}
}
My Background class
package com.projectelrond.main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class BackGround extends JPanel {
private static final long serialVersionUID = 1L;
public BufferedImage Bg;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(Bg, 0, 0, null);
}
public BackGround() {
try {
Bg = ImageIO.read(new File("src/Images/BG.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
and last but not least the sprite that I am trying to add
package com.projectelrond.Sprites;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Ranger extends JPanel{
private static final long serialVersionUID = 1L;
public BufferedImage RangerIm;
public Ranger() {
try {
RangerIm = ImageIO.read(new File("src/Images/Sprites/Ranger.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(RangerIm, 0, 0, null);
}
}
Thanks for all the help and if there are any tips that you wish to share they will be much obliged.
g.drawImage(RangerIm, 0, 0, null);
You are drawing the image at its actual size. There is no need to do custom painting for this. You would do custom painting if you want to scale the image.
Instead you can just use a JLabel with an ImageIcon:
BufferedImage rangerIm = ImageIO.read(new File("src/Images/Sprites/Ranger.png"));
JLabel ranger = new JLabel( new ImageIcon(rangerIm) );
ranger.setSize( ranger.getPreferredSize() );
BufferedImage backgroundIm = Bg = ImageIO.read(new File("src/Images/BG.png"));
JLabel background = new JLabel( new ImageIcon(rangerIm) );
background.add( ranger );
f.add(background, BorderLayout.CENTER);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.pack();
f.setVisible(true);
Now the ranger is added to the background which is added to the frame. Also, you need to add the components to the frame BEFORE the frame is visible(). The pack() method will make the frame the size of the background image.
I'm trying to display an image in a window using Swing.
For some reason, when I run the program, the dialog box that displays contains nothing. Is there a clear reason why this is happening?
public class GameScreen {
public static void main(String[] args) {
GameView view = new GameView();
view.setVisible(true);
}
}
public class GameView extends JFrame {
public MapView mapPanel;
public void GameView() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mapPanel = new MapView();
this.add(mapPanel);
this.pack();
this.setLocationByPlatform(true);
}
}
public class MapView extends JPanel {
public MapView() {
ImageIcon map = new ImageIcon("map.jpeg");
JLabel mapLabel = new JLabel(map);
this.add(mapLabel,BorderLayout.CENTER);
}
}
On a side note, I've heard that using ../../ in file path names isn't recommended, however in most application packages the 'resources folder' is located in the parent directory of the executable files, so what is the main way people get around this?
Here's one way to draw an image on a JPanel using Swing.
In order for this code to work, you have to put the image in the same directory as the Java code.
If you want to put the image in a different directory, you have to make that directory part of the Java classpath, and add a slash to the front of the file name.
package com.ggl.testing;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class DrawImage implements Runnable {
#Override
public void run() {
JFrame frame = new JFrame("Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(new ImagePanel(getImage()));
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawImage());
}
public class ImagePanel extends JPanel {
private static final long serialVersionUID = -2668799915861031723L;
private Image image;
public ImagePanel(Image image) {
this.image = image;
this.setPreferredSize(new Dimension(image.getWidth(null), image
.getHeight(null)));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
}
I'm trying to set up face detection with JavaCV. I've got working code with cvLoadImage but when I try to load an image via Highgui.imread there's an error: 'Highgui cannot be resolved' and 'Highgui' has red wavy underlining. For some reason Eclipse cannot deal properly with imported com.googlecode.javacv.cpp.opencv_highgui or ...?
Problem here:
CvMat myImg = Highgui.imread(myFileName);
Full code:
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
import com.googlecode.javacv.cpp.opencv_core.CvRect;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSeq;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_objdetect.CvHaarClassifierCascade;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import java.awt.Button;
import java.io.File;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMat;
import com.googlecode.javacv.cpp.opencv_highgui;
//import opencv_highgui;
public class Form1 {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
String myFileName = "";
//Load haar classifier XML file
public static final String XML_FILE =
"resources/!--master--haarcascade_frontalface_alt_tree.xml";
private JFrame frame;
//Detect for face using classifier XML file
public static void detect(IplImage src){
//Define classifier
CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(cvLoad(XML_FILE));
CvMemStorage storage = CvMemStorage.create();
//Detect objects
CvSeq sign = cvHaarDetectObjects(
src,
cascade,
storage,
1.1,
3,
0);
cvClearMemStorage(storage);
int total_Faces = sign.total();
//Draw rectangles around detected objects
for(int i = 0; i < total_Faces; i++){
CvRect r = new CvRect(cvGetSeqElem(sign, i));
cvRectangle (
src,
cvPoint(r.x(), r.y()),
cvPoint(r.width() + r.x(), r.height() + r.y()),
CvScalar.RED,
2,
CV_AA,
0);
}
//Display result
cvShowImage("Result", src);
cvWaitKey(0);
}
/**
* Create the application.
*/
public Form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
JLabel Label1 = new JLabel(" ");
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 301, 222);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnDetect = new JButton("Detect");
btnDetect.setVerticalAlignment(SwingConstants.TOP);
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//IplImage img = cvLoadImage("resources/lena.jpg");
IplImage img = cvLoadImage(myFileName);
CvMat myImg = Highgui.imread(myFileName);
detect(img);
}
});
frame.getContentPane().add(btnDetect, BorderLayout.SOUTH);
Label1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Label1, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Open");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Открыть файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
myFileName = file.getAbsolutePath();
Label1.setText(myFileName);
}
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 window = new Form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//Load image
//IplImage img = cvLoadImage("resources/lena.jpg");
//detect(img);
}
}
External JARs: http://pasteboard.co/jwqNHC9.png
Full project in ZIP
I've also followed all steps from here: http://opencvlover.blogspot.in/2012/04/javacv-setup-with-eclipse-on-windows-7.html
Any help will be appreciated.
Mat m = Highgui.imread(myFileName); is from the builtin opencv java wrappers , not from javacv ( which is a independant, 3rd party wrapper ).
unfortunately, both concurrent apis are pretty incompatible, as javacv is wrapping the outdated c-api, and the opencv ones are wrapping the more modern c++ api.
I am attempting to add background music to my program but when i specify the path to the audio file i get the error message. How else can I specify this(this is going to be sent to another person). So the path cannot be on my system, it must be located in the JAR as well.
package main;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Main extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
PlaySound();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public static void PlaySound() {
InputStream in;
try {
in = new FileInputStream(new File("/audio/Happy_Happy_Birthday.wav"));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 717, 508);
contentPane = new JPanel() {
/**
*
*/
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(
Main.class.getResource("/images/happy_birthday.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
Load the clip using an URL rather than a File. By the time of deployment, those resources will likely become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.
Play the sound using a javax.sound.sampled.Clip (as opposed to undocumented classes in the sun.audio package). See the Java Sound info. page for working source.
InputStream in;
try {
in = new FileInputStream(new File("Jock_Jams_-_Are_You_Ready_For_This.wav"));
AudioStream audios = new AudioStream(in);
AudioPlayer.player.start(audios);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I use this outside of my while loop and it works as long as if you don't mind it not being able to stop.
I am trying to do my final project for my java class. I am attempting to take a .png picture and use it as a component that I can add to my JFrame. However, when I try to do this it throws an exception and does what is in the catch statement. I do not understand why it would do this. I have the .png file in the same folder as my .java files.
package InventoryApp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
/**
*
* #author Curtis
*/
public class FinalProject extends DFrame
{
//main method
public static void main(String[] args)
{
start();
}
//building splash screen
public static void start()
{ DFrame splashFrame = new DFrame();
try
{
BufferedImage myPicture = ImageIO.read(new File("logo.png"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
splashFrame.add(picLabel);
}
catch(IOException g)
{
JLabel error = new JLabel("Picture Could Not Be Found");
splashFrame.add(error);
}
JButton create = new JButton("Click to Create Item List");
JButton view = new JButton("Click to View Item List");
splashFrame.add(create);
splashFrame.add(view);
}
}
When you create a File object with no path specified, it assumes the directory the program was launched from, not the directory the current class file is in. You probably want to instead use FinalProject.class.getResource():
BufferedImage myPicture = ImageIO.read(FinalProject.class.getResource("logo.png"));