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 :)
Related
I am new to Java and am having a problem with my JAR file loading some graphic resources. I am using IntelliJ IDEA 2021.2 (Ultimate Edition) to write my code. While in the IDE, the code work fine and the resources are loaded, but once I create the JAR file, and run it, thew graphics don't show. I should mention I do have some graphics that show, as explained below:
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
public class ClassTopFrame extends JPanel{
public ClassTopFrame(int screenWidth, int screenHeight) {
this.setBackground(Color.BLACK);
this.setBounds(160, 0, screenWidth-160, screenHeight/2);
JLabel jl=new JLabel();
jl.setIcon(new javax.swing.ImageIcon(Objects.requireNonNull(getClass().getResource("/i_TMEA-0002-J_Logo.png"))));
this.add(jl);
}
}
This class load the image as expected. However when I try to load button images for my menu, the buttoin images do not load. Here is the class I use to create my buttons.
package com.troymarkerenterprises;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
public class TMButton extends JButton {
Font okuda;
public TMButton(String text, String color) {
try {
okuda = Font.createFont(Font.TRUETYPE_FONT, new File("res/f_okuda.ttf")).deriveFont(16.0F);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("res/f_okuda.ttf")));
} catch (IOException | FontFormatException ignored){
}
ImageIcon defaultIcon = new ImageIcon("res/b_" + color + "_default.png");
ImageIcon hoverIcon = new ImageIcon("res/b_" + color + "_selected.png");
ImageIcon disabledIcon = new ImageIcon("res/b_disabled.png");
this.setForeground(Color.BLACK);
this.setFont(okuda);
this.setText("<html><body><br><br>"+text+"</body><html>");
this.setHorizontalTextPosition(SwingConstants.CENTER);
this.setVerticalTextPosition(SwingConstants.CENTER);
this.setIcon(defaultIcon);
this.setSelectedIcon(hoverIcon);
this.setDisabledIcon(disabledIcon);
this.setMinimumSize(new Dimension(124,70));
this.setBorder(null);
this.setBorderPainted(false);
this.validate();
}
}
As I said, I am baffled as to why this is not working. I am not sure if my project structure is wrong, or if I am creating my JAR file incorrectly. To create the JAR file I am going to IntelliJ's project structure option and creating an Artifact. After I build the Artifact, I set the executable bit in my systems file explorer, and run the far file.
I would appreciate any help anyone can suggest. If I have left something out in my explanation of the problem, I have my entire app post on my GitHub page at: https://github.com/troy-marker/TMEA-0002-J.
Thanks for any assistance, Troy.
Problem is solved. Thank you to g00se for pointing out my error.
In one case, you're filling the image icons with resources, and the other you're filling them with files. You should use the former method at all times
I was trying to load the graphics two different ways, and did not realize it. Thank you for the help.
I was thinking to set an image as background instead of a solid color. Is that possible?
Here are the codes of my MainApp.java
package com.gabriel.guiApp;
import java.awt.Color;
import javax.swing.JFrame;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
import com.gabriel.guiImpl.Car;
public class MainApp extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
MainApp mainApp=new MainApp();
mainApp.setTitle("Draw");
mainApp.setBounds(10,10, 1200, 400);
Draw draw= new Draw();
draw.setBounds(0,0, 80,80);
draw.setBackground(Color.red);
draw.setForeground(Color.yellow);
draw.init();
mainApp.add(draw);
ClassPathResource r= new ClassPathResource("ApplicationContext.xml");
BeanFactory factory=new XmlBeanFactory((org.springframework.core.io.Resource) r);
Car car=(Car) factory.getBean("car");
draw.setCar(car);
mainApp.setVisible(true);
}
}
Please insert your solution to my code. Thank you!
I believe there's no helper method that does this for you. This type of question has been asked and answered before, so i would just share a link to the accepted answer. You could look at other examples on that thread too and then choose the one that best suits you.
https://stackoverflow.com/a/1466278/12796448
Look at this example too
https://www.tutorialspoint.com/how-to-add-background-image-to-jframe-in-java
I believe the best way to achieve what you want is to paint the background of your container with the desired image. Look at the links i shared, they might help.
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...
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 have a general question about java. Because I want to create StronaGlowna.java (class) where I have place all buttons, check box and other GUI component which I want to display in main class. The first question is this right way, it's correct ? or maybe is better way to do this thing. My code look this:
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Main extends JFrame {
private static final long serialVersionUID = -4575271483481196192L;
Container pane;
CardLayout layout;
public Main() throws FileNotFoundException, IOException {
layout = new CardLayout();
setLayout(layout);
pane = this.getContentPane();
/*Page: Strona główna */
JPanel newPanel = new JPanel();
pane.add("New", newPanel);
JButton przycisk = new JButton("Przycisk");
newPanel.add(przycisk);
...
In "pane.add("New", newPanel);" I want to display elements from:
package aplikacja.glowna;
import javax.swing.JButton;
import javax.swing.JPanel;
public class StronaGlowna {
public void StronaGlownaDisplay() {
JPanel newPanel = new JPanel();
JButton przycisk2 = new JButton("Przycisk");
newPanel.add(przycisk2);
}
}
Can I import/display all class StronaGlowna in main() something like a include in PHP ? What do You thing about my idea, it's correct or I'm wrong ? Thanks for help and discussion.
It sounds like the way Netbeans handling GUI. You may view the article in http://netbeans.org/kb/docs/java/quickstart-gui.html, it may help you understand how the GUI works since Netbeans can generate code for you. You can always import class and create object to access methods (often public methods) . I think it is not like a include in PHP. PHP include is like to directly include the source code, but jave is not.
First - Never, never, never, code in Main class. Call a method from it and then start your staff in another class. And, of course, don't extend it. And the constructor is neither a good idea. All of these are bad practices. Now, going into your problem, my suggestion is that you make StronaGlowna extend JPanel, and then obtain an instance of it through a public constructor, and use that instance as the parameter for the constructor of JScrollPane. That will make the scrollPane act as a 'screen' inside which you can see the contents of StronaGlowna, which is what I understand you're after.