I'm a beginner in Java and I followed a tutorial to write this program (yes, I that much of a beginner) and it works perfectly when I run it on Eclipse. It also runs great on the computer I coded it on. However, if I send it to another computer (just the .jar file) and run it, it fails because it can't find the icon. Here is everything I've got. The icon I'm using is saved in the bin folder along with all the class files for the program. For privacy reasons, I replaced certain lines with "WORDS".
The tutorial I followed in two parts:
Part 1 - https://buckysroom.org/videos.php?cat=31&video=18027
Part 2 - https://buckysroom.org/videos.php?cat=31&video=18028
My main class (I called it apples cause the tutorial did).
import javax.swing.JFrame;
public class apples {
public static void main(String[] args) {
Gui go = new Gui();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(1920,1080);
go.setVisible(true);
}
}
And now my second class, "Gui":
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Gui extends JFrame {
private JButton custom;
public Gui () {
super("WORDS");
setLayout(new FlowLayout());
Icon b = new ImageIcon(getClass().getResource("b.png"));
custom = new JButton(null, b);
custom.setToolTipText("WORDS");
add(custom);
HandlerClass handler = new HandlerClass();
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
JOptionPane.showMessageDialog(null, String.format("WORDS", event.getActionCommand()));
}
}
}
Thank you so much for helping!
It's worth reading Loading Images Using getResource where it's explained in detail along with loading images from jar as well.
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("b.png"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/b.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/b.png"))
Read more...
Related
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.sound.midi.Patch;
import javax.swing.*;
this is were the code start
public class graficCar extends JComponent
{
private ImageIcon image1=null;
private JLabel label1=null;
private ImageIcon image2=null;
private JLabel label2=null;
graficCar(){
setLayout(new FlowLayout());
the problem here
image1=new ImageIcon(getClass().getResource("4596067.png"));
label1=new JLabel(image1);
add(label1);
}
the main
public static void main(String[] args)
{
graficCar g=new graficCar();
g.setDebugGraphicsOptions(JFrame.EXIT_ON_CLOSE);
g.setVisible(true);
}
As you mentioned, your png file is in C:\Users\user\Downloads folder. I bet class is somewhere else.
The problem is getResource() finds file in classpath by default. Here you could find details if you want to go deeper.
One solution is to put .png right next to your .java class but it's bad practice. More convenient way described here. The best practice is to create special folder for your resources in the project and then use relative path to it. How to do this is out of scope although it's described in many sites and in Stackoverflow too. Don't hesistate to use Search :)
Using Eclipse Mars, I copied a tiny Java program from the Internet that displays a small window containing a "Click me!" JButton and a JLabel. Every time you click the button, the label is updated to show the total number of clicks. Trying to learn about Java packages, I added this package statement at the top:
package nineteen_3;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String [] args {
...
}
}
This code worked fine.
Learned the trick of making a JButton that looks like a JLabel, Decided to make a package of new objects beginning with KLabel, a modified JButton.
package laobjects;
import javax.swing.JButton;
public class KLabel extends JButton {
...
}
No compile errors.
Back in Main {}, I added this import statement for KLabel. Below are existing import statements:
import laobjects.KLabel;
... and get: The import laobjects cannot be resolved
And in the Main {} code:
KLabel lbl = new KLabel("Count: 0");
I'm getting KLabel cannot be resolved to a type
Both the Package and Project Explorers show 'KLabel' as hi-level entries:
KLabel
src
laobjects
KLabel.java
KLabel
label
KLabel(String)
So I've just written down some simple code that just displays an image in a JButton.
What I have done is write the code:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame{
public static ImageIcon bf;
public static JPanel p;
public static JButton b;
public static void main (String args[]){
Main main = new Main();
bf = new ImageIcon("car.png");
p = new JPanel();
b = new JButton(bf);
p.add(b);
main.add(p);
main.setVisible(true);
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setSize(600,700);
}
}
And I have copied a pic named car.png in the same folder with my class, but I can't seem to get it to work in elipse.
But when I run the same exact code in BlueJ it runs it without any known issues.
Any help woul be greately apprecciated
Thanks In advance.
change
bf = new ImageIcon("car.png");
to
URL url = Main.class.getResource("car.png");
bf = new ImageIcon(url);
Check that if car.png is under the bin directory in the filesystem (it is filtered out in Eclipse, so do it in a file explorer).
Btw I would suggest using something like ImageIO.read(Main.class.getResource("/car.png")). The reason is the following: later on you will probably package your app (into a Jar file for example). Now if you do it this way, Java is able to locate the image even if it is executed as a Jar or from
I am java newbie.
I was reading a tutorial book, and tried almost all code given as examples, and they all worked perfectly. But, when I tried this audio playing tutorial, even though I understood most of it, I still can't make it play. It gives me error, saying
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at MouseClicker.main(MouseClicker.java:9)
Here is the code.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
import java.net.URL;
public class MouseClicker extends Jframe{
AudioClip click;
public static void main(String[] args){
new MouseClicker();
}
public MouseClicker(){
this.setSize(400,400);
this.setTitle("Mouse Clicker");
this.addMouseListener(new Clicker());
URL urlClick = MouseClicker.class.getResource("hello.wav");
click = Applet.newAudioClip(urlClick);
this.setVisible(true);
}
private class Clicker extends MouseAdapter
public void mouseClicked(MouseEvent e){
click.play();
}
}
public class MouseClicker extends Jframe{
It's a JFrame, not a Jframe. (capital F)
Remember, Java is case sensitive!
You're missing an opening brace in the definition of the Clicker class
private class Clicker extends MouseAdapter {
^
A Java IDE can highlight these syntax errors.
Also ensure that the audio file hello.wav is located in the same location as MouseClicker.class (the bin folder in this case) so that it can be read as a resource.
I'm writing an application in Java using JPL provided by SWI-Prolog to call Prolog from Java.
I'm using Eclipse as the IDE. I don't know how to start this example I found online:
Here the java code:
package prolog;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import jpl.Atom;
import jpl.Compound;
import jpl.Variable;
import jpl.Term;
import jpl.Query;
import jpl.JPL;
#SuppressWarnings({ "unchecked", "deprecation", "serial" })
public class JavaProlog extends JFrame {
JButton startButton = new JButton("Start");
JTextArea textArea = new JTextArea("A Diagnostic Expert System \n" +
"for respiratory diseases and lung.");
/**
*/
JavaProlog(){
Container cp=getContentPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation (200,200);
setSize (300,200);
setLayout (new FlowLayout());
startButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
startDiagnose();
}
});
cp.add(textArea);
cp.add(startButton);
setVisible(true);
}
private void startDiagnose(){
Term consult_arg[] = {
new Atom( "C://Users//i_vista//workspace//mdc.pl" )
};
Query consult_query =
new Query(
"consult",
consult_arg );
boolean consulted = consult_query.query();
if ( !consulted ){
System.err.println( "Consult failed" );
System.exit( 1 );
}
}
public static void main( String argv[] ){
JPL.init();
JavaProlog jpTest = new JavaProlog();
}
If I run the Prolog program directly from Prolog it works fine and the same when I call it from the Java application.
I can also see the output in the Eclipse console and I can reply to the questions.
But I would like to build a Java UI for the interaction between the user and the system but I don't know how to take the code from Prolog in Java and put it in the UI.
For example how can I capture input from the Java UI and pass this to the Prolog code?
Problem is probably that your Prolog text is not written in
inverted style, as for example Java UI applications typically are.
So start your Prolog system in a separate thread. Replace all read/1 and write/1
in your Prolog text by roughly:
my_read(Prompt,Value) :- set_UI_prompt(Prompt), wait(signal), get_UI_value(Value).
my_write(Label,Value) :- set_UI_result(Label, Value).
Since also running in a second separate thread, upon entering a value
and hitting some button, the UI application should notify(signal).
Or rewrite the logic of the expert system, so that the inferences
leading to a query or answer can be called from the outside in a step
wise fashion. But also then spawning a thread is recommended, since
the inference might take time.
Best Regards
P.S.: If youre application were inverted, you could easily make
it a couple of different UIs:
http://www.jekejeke.ch/idatab/doclet/prod/en/docs/10_pro08/13_press/02_deploy/package.html