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"));
Related
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.
I am creating a user interface for a pdf reader, and I want to have a list with recent open files. (Not the content of the files, just the name of the file).
From the snap shared, I assume that you are using JFileChooser for your dialog to open file. Hope this helps!
int result = fileChooser.showOpenDialog(panel);
//where panel is an instance of a Component such as JFrame, JDialog or JPanelwhich is parent of the dialog.
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
textArea.setText(selectedFile.getName());
}
The example below uses a JFileChooser with setMultiSelectionEnabled(true) to add() one or more files to a List<File> and update() a JTextArea with the current list. As suggested here, you can use Action to maintain a menu or tool bar of recent files.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
* #see https://stackoverflow.com/a/37153404/230513
* #see https://stackoverflow.com/a/4039359/230513
*/
public class Test {
private final List<File> recentFiles = new ArrayList<>();
private final JTextArea textArea = new JTextArea(12, 12);
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setBorder(BorderFactory.createTitledBorder("Recent Files"));
f.add(textArea);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Open") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(".");
jfc.setMultiSelectionEnabled(true);
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
recentFiles.addAll(Arrays.asList(jfc.getSelectedFiles()));
update();
}
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private void update() {
textArea.setText("");
for (File file : recentFiles) {
textArea.append(file.getName() + "\n");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
today I kinda fiddled around with image opening/scaling/displaying in Java and wrote a bit of code to open an Image File, scale it randomly and display it for a short time.
The problem is: After displaying it for like 100-1000 times, the used memory of my "javaw.exe" grows and grows, it even reached 1 GB of memory space.
I dont know where the memory leak in my code is since the only memory eating things are my picures and there are only 2 (the original image and the one who is getting scaled, which is always assigned to the same variable(temp) so the "older" ones should be picked off by the GC), maybe you guys could have a look over it, its pretty simple.
1) You choose an image from your hard drive
2) It gets scaled randomly
3) Its displayed for a short amount of time and then disappears
4) go to 2)
To scale the image I used this library: http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.imgscalr.Scalr;
public static void main(String[] args) throws IOException, InterruptedException {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
BufferedImage originalImage = ImageIO.read(chooser.getSelectedFile());
BufferedImage temp;
while(true){
int width = (int) ((Math.random()*1000)+1);
int height = (int) ((Math.random()*1000)+1);
Thread.sleep(1000);
temp = Scalr.resize(originalImage,Scalr.Mode.FIT_EXACT, width, height);
showImage(temp, 800);
}
}
static void showImage(BufferedImage v,long length) throws InterruptedException {
JFrame frame = new JFrame();
frame.add(new JLabel(new ImageIcon(v)));
frame.setSize(v.getWidth(), v.getHeight());
frame.setVisible(true);
Thread.sleep(length);
frame.setVisible(false);
}
This is my first time posting here, so please ask questions if I am unclear
thanks in advance!
EDIT: I monitored the memory javaw.exe is needing
1 picture displayed: 75M
100 pictures displayed: 330M
1000 pictures displayed: 2,4G
EDIT 2:
I now have applied your helpful advice but I still have a growing amount of memory and my Images arent displayed anymore.. The JFrames are empty.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.imgscalr.Scalr;
public class App {
public static void main(String[] args) throws IOException, InterruptedException {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
BufferedImage originalImage = ImageIO.read(chooser.getSelectedFile());
BufferedImage temp;
JFrame frame = new JFrame();
while(true){
int width = (int) ((Math.random()*1000)+1);
int height = (int) ((Math.random()*1000)+1);
Thread.sleep(1000);
temp = Scalr.resize(originalImage,Scalr.Mode.FIT_EXACT, width, height);
showImage(temp, 500, frame);
}
}
static void showImage(BufferedImage v,long length, JFrame frame) throws InterruptedException {
SwingUtilities.invokeLater(
() -> {
frame.removeAll();
frame.revalidate();
frame.repaint();
frame.add(new JLabel(new ImageIcon(v)));
frame.setSize(v.getWidth(), v.getHeight());
frame.setVisible(true);
try {
Thread.sleep(length);
} catch (Exception e) {}
frame.setVisible(false);
frame.dispose();
});
}
}
Maybe I put your advice in the wrong places in my code.
The code below should do what you want. I used a Timer instead of Thread.sleep. You're tying up the EDT. I also just draw the image in the container. You should probably use a JPanel instead (add it to the JFrame and override its paintComponent method). I also cleaned up the methods a little.
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import org.imgscalr.Scalr;
public class App extends JFrame implements ActionListener{
BufferedImage originalImage = null;
BufferedImage temp = null;
JFileChooser chooser = null;
public App(){
setVisible(true);
}
public static void main(String[] args) throws IOException, InterruptedException {
SwingUtilities.invokeLater(
() -> {
App app = new App();
Timer timer = new Timer(1000, app);
timer.start();
});
}
#Override
public void actionPerformed(ActionEvent ae){
if(null == chooser){
chooser = new JFileChooser();
chooser.showOpenDialog(this);
loadImage();
}
showImage();
repaint();
}
#Override
public void paint(Graphics g){
super.paint(g);
if(null == temp){
return;
}
g.drawImage(temp, 0, 0, null);
}
public void loadImage(){
try{
originalImage = ImageIO.read(chooser.getSelectedFile());
} catch(IOException ioe){
ioe.printStackTrace();
}
}
public void showImage() {
int width = (int) ((Math.random()*1000)+1);
int height = (int) ((Math.random()*1000)+1);
temp = Scalr.resize(originalImage,Scalr.Mode.BEST_FIT_BOTH, width, height);
setSize(width, height);
}
}
You might want to try
originalImage.flush();
originalImage = null;
temp.flush();
temp = null;
but there is no guarantee when your image will get garbage collected
Apart from that you should also consider clearing and reusing the same JFrame.
removeAll();//or remove the previous JLabel
revalidate();
repaint();
Also the proper way to display a JFrame is by using the SwingUtilities invokeLater method to make sure this "job" is placed on the Event Dispatch Thread (EDT).
// schedule this for the event dispatch thread (edt)
SwingUtilities.invokeLater(yourJFrame);
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.