Issues with ImageIcon and images on buttons - JFrame - java

this has been driving me crazy all day so I figured I'd post it here and see if someone else can work it out. First off I tried to add a background image, the default ImageIcon was not working so I went with overriding the paint method instead. #
public class ImageJPanel extends JPanel {
private static final long serialVersionUID = -1846386687175836809L;
Image image = null;
public ImageJPanel(){
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
ImageJPanel.this.repaint();
}
});
}
//Set the image.
public ImageJPanel(Image i) {
image=i;
setOpaque(false);
}
//Overide the paint component.
public void paint(Graphics g) {
if (image!=null) g.drawImage(image, 0, 0, null);
super.paint(g);
}
}
Once I used that it worked fine, however now I want to add images to my buttons but it is not working. Here is how my buttons work:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Images images = new Images();
JPanel j = new ImageJPanel(images.menuBackground);
j.setLayout(null);
JButton Button_1= new JButton("Button_1",new ImageIcon("images/gui/Button.png"));
Insets insets = j.getInsets();
Dimension size = Button_1.getPreferredSize();
Button_1.setBounds(300 + insets.left, 150+ insets.top, size.width, size.height);
Singleplayer.setSize(200, 50);
j.add(Button_1);
frame.add(j);
frame.setSize(800,600);
frame.setResizable(false);
Button_1.addMouseListener(singleplayerPressed);
frame.setVisible(true);
All my images are .png, could that affect it?

Let's start with this:
public void paint(Graphics g) {
if (image!=null) g.drawImage(image, 0, 0, null);
super.paint(g);
}
This is the wrong approach. Firstly, you really don't want to override the paint method UNLESS you absolutely know that this is the correct approach to your problem (and without knowing more, I'd suggest it isn't).
Secondly, you paint your image on the component, then promptly paint over the top of it...(super.paint(g); can have the ability to paint over your work, I know the panel is opaque, but this is still a very bad approach).
Use paintComponent instead
protected void paintComponent(Graphics g) {
super.paint(g);
if (image!=null) g.drawImage(image, 0, 0, null);
}
PNG images are fine, they are supported by Swing out of the box.
Make sure that your program can see the image. Is it been loaded from the file source or is it a resource within you JAR?
Try this:
System.out.println(new File("images/gui/Button.png").exits());
If your program can see the file, it will return true other wise the program can not see the file and that is your problem.

Try this:
ImageIcon image = new ImageIcon(this.getClass()
.getResource("images/gui/Button.png"));
Side note, you should override paintComponent() not paint(). Also make sure to call super implementation before doing all your painting. For more details see Lesson: Performing Custom Painting tutorial.

Related

How to add new Label(png) to GUI in the controller class? [duplicate]

I am new to making GUIs so I decided to try the the windows builder for eclipse, and while great I do have some doubts. I have been searching but I cannot seen to find a good way to add a background image to my "menu". For example I tried this:
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 300, 250); //Dimensiones
contentPane = new JPanel() { //Imagen de Fondo
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(
Menu.class.getResource("/imgs/rotom.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
And adding the following classes:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
But to no avail the window remains with its dull grey color, so far my code is just the standard one WindowsBuilder cooks for you plus 4 buttons but I doubt they're of importance here. Shouldn't the code I added override the paintComponent() method of the jPanel and draw the image in it?
The class for the menu is in a package within my project and the image is within a imgs package is within the same project as well.
Thanks a lot in advance.
A simple method, if you're not interested in resizing the background image or applying any effects is to use a JLabel...
BufferedImage bg = ImageIO.read(Menu.class.getResource("/imgs/rotom.jpg"));
JLabel label = new JLabel(new ImageIcon(bg));
setContentPane(label);
setLayout(...);
There are limitations to this approach (beyond scaling), in that the preferred size of the label will always be that of the image and never take into account it's content. This is both good and bad.
The other approach, which you seem to be using, is to use a specialised component
public class BackgroundPane extends JPanel {
private BufferedImage img;
public BackgroundPane(BufferedImage img) {
this.img = img;
}
#Override
public Dimension getPreferredSize() {
return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
}
You should avoid trying to perform any task in the paintComponent method which may take time to complete as paintComponent may be called often and usually in quick succession....
Getting the image to scale when the component is resized is an entire question into of it self, for some ideas, you could take a look at...
Java: maintaining aspect ratio of JPanel background image
Java: JPanel background not scaling
Quality of Image after resize very low -- Java
Reading/Loading images
Oh, and, you should avoid extending directly from top level containers, like JFrame, they reduce the reusability for your components and lock you into a single container

Adding a background image to my Java Applet [duplicate]

I am new to making GUIs so I decided to try the the windows builder for eclipse, and while great I do have some doubts. I have been searching but I cannot seen to find a good way to add a background image to my "menu". For example I tried this:
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 300, 250); //Dimensiones
contentPane = new JPanel() { //Imagen de Fondo
public void paintComponent(Graphics g) {
Image img = Toolkit.getDefaultToolkit().getImage(
Menu.class.getResource("/imgs/rotom.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
};
And adding the following classes:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
But to no avail the window remains with its dull grey color, so far my code is just the standard one WindowsBuilder cooks for you plus 4 buttons but I doubt they're of importance here. Shouldn't the code I added override the paintComponent() method of the jPanel and draw the image in it?
The class for the menu is in a package within my project and the image is within a imgs package is within the same project as well.
Thanks a lot in advance.
A simple method, if you're not interested in resizing the background image or applying any effects is to use a JLabel...
BufferedImage bg = ImageIO.read(Menu.class.getResource("/imgs/rotom.jpg"));
JLabel label = new JLabel(new ImageIcon(bg));
setContentPane(label);
setLayout(...);
There are limitations to this approach (beyond scaling), in that the preferred size of the label will always be that of the image and never take into account it's content. This is both good and bad.
The other approach, which you seem to be using, is to use a specialised component
public class BackgroundPane extends JPanel {
private BufferedImage img;
public BackgroundPane(BufferedImage img) {
this.img = img;
}
#Override
public Dimension getPreferredSize() {
return img == null ? super.getPreferredSize() : new Dimension(img.getWidth(), img.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
}
You should avoid trying to perform any task in the paintComponent method which may take time to complete as paintComponent may be called often and usually in quick succession....
Getting the image to scale when the component is resized is an entire question into of it self, for some ideas, you could take a look at...
Java: maintaining aspect ratio of JPanel background image
Java: JPanel background not scaling
Quality of Image after resize very low -- Java
Reading/Loading images
Oh, and, you should avoid extending directly from top level containers, like JFrame, they reduce the reusability for your components and lock you into a single container

Is there ever a reason drawImage won't actually draw an image?

private void renderLevelBackground(Graphics2D g2) {
Image backgroundImage = model.getBackgroundImage();
g2.drawImage(backgroundImage, 0, 0, null);
}
This is my code, I know that the backgroundImage is loaded properly because if I getWidth/Height it gives me the correct values. Is there anyway to test if it's the image or if it's the method somehow? It just won't draw on my screen despite the fact that I've used the drawImage method many times in this project already, all of which work flawlessly.
Thanks
"Is there ever a reason drawImage won't actually draw an image?"
Possibility, there is no image due to a bad path provided. Use ImageIO.read() which will cause an exception if the image file is not found. For example
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(getClass().getResource("/resources/image.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If the image is not found, it will throw an IO exception.
Possibility, the panel to which you are drawing, has no preferred size (0 x 0), and you are adding it a container wit layout that respects preferred sizes, so the ImagePanel will not be able to show the image. For example
public class ImagePanel extends JPanel {
protected void paintComponent(...) {
...
}
JPanel panel = new JPanel(); // default FlowLayout that respects preferred sizes
panel.add(new ImagePanel());
To fix this, you can override the gerPreferredSize() of the ImagePanel
public class ImagePanel extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
Possibility, you are not calling your method within the graphics context of the paint[Component] method.
protected void paintComponent(Graphics 2d) {
super.paintComponent(g);
Grapchics2D g2 = (Graphics2D)g;
renderLevelBackground(g2);
}
Other than that, these are all just guesses, and you should provide some more code code (preferably an MCVE) to help us better help you with the problem.
Possible Alternative to your approach. It seems like (from the little code snippet and it method signature semantics) you want to change the background image, when a level have changed. Consider using setBackgroundImage(BufferedImage image) method in your panel class, when the image is drawn. You can then set the background, whenever need be. Something like
public class BackgroundPanel extends JPanel {
private BufferedImage backgroundImage;
public void setBackgroundImage(BufferedImage image) {
this.backgroundImage = image;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Grpahics2D g2 = (Graphics2D)g;
if (image != null) {
g2.drawImage(backgroundImage, 0, 0, this);
}
}
}
So whenever you call setBackgroundImage, the image will change, and be repainted.
You may need to explicitly tell the JComponent that you are painting onto that it needs to be redrawn with revalidate() and repaint()

Scrolls not appears

I want add JScrolpane to JPanel, but that not appears. In JLabel works fine and its very easy. I am using JPanel beacuse I'll add some image proccessing stuff to my program. There is my code:
public void draw(){
panel=new JPanel(){
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(image, 0, 0, this);
g2.dispose();
}
};
panel.setBorder(BorderFactory.createEtchedBorder());
panel.setPreferredSize(new Dimension(400, 330));
s=new JScrollPane(panel);
s.setPreferredSize(new Dimension(400,285));
this.getContentPane().add(s,BorderLayout.CENTER);
add(panel);
revalidate();
repaint();
}
s=new JScrollPane(panel);
s.setPreferredSize(new Dimension(400,285));
this.getContentPane().add(s,BorderLayout.CENTER);
add(panel); // ****** ????????????
revalidate();
repaint();
}
You're adding the JPanel to the GUI not the JScrollPane, so you really shouldn't expect to see any scrollpanes if they've not been added anywhere.
Solution: Add your JScrollPane, s, that holds the JPanel to the GUI, not JPanel itself.
You dont honor the paint chain, call super.paintComponent(g) as first call in overridden paintComponent method. i.e
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
//draw here
}
or visual artifacts may occur.
Also note the #Override annotation which should be used with overridden methods in order to gain the advantage of compiler checking that we overrode the method correctly.
There is no need for getContentPane().add(..) simply call add on JFrame instance as add(..) along with remove(..) and setLayout(..) have been forward to the JFrames contentPane
Also not a good idea to go extending JFrame for nor reason, simply create an instance and use that i.e:
JFrame frame=new JFrame("Title here");
...
frame.add(..);
...
frame.pack();
frame.visible(true);
Also draw onto the Graphics object passed into paintComponent g dont go creating your own in paintComponent. Unless of course you're doing if for the reason #HFOE mentioned in below comment :).
No need for this parameter in drawImage(..) unless your JPanel implements on ImageObserver or the image may not be fully loaded when painting occurs. Simply use null.
And just for the cherry on top use some Graphics2D and RenderHints as seen here. This will allow for a better quality image to be drawn and text.
I got it! The main reason for me was no-layout manager and no-declarated size of this. There is my code:
public void draw(){
panel=new JPanel(new BorderLayout()){
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, null);
}
};
panel.setBounds(0, 0, img.getWidth(), img.getHeight());
panel.setPreferredSize(new Dimension(img.getWidth(),obraz.getHeight()));
JScrollPane scrolls=new JScrollPane(panel,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrolls);
validate();
repaint();
}
But if someone will want copy this code in the future, there is one thing to be known- a size of Jpanel isn't refreshing (it's always one size of first opened image), but I have scrolsl and I am satisfied for now ;). Thanks a lot for everyone.

How do i have a background image resize in a java gui?

So im making a gui, and i have a background image for it. i dont know how to make it set as the background, so any help with that would be good. an explination would also be good. also, after we get that image as a background, how do we get the image resize to the size of the window. such as
image.setSize(frame.getHeight(), frame.getWidth());
but i dont know if that would work. the image name is ABC0001.jpg and the frame name is frame. thanks!
To get the image to resize, you can either use
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this); // draw the image
}
or you can use a componentlistener, implemented like:
final Image img = ...;
ComponentListener cl = new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
Component c = ce.getComponent();
img = im1.getScaledInstance(c.getWidth(), c.getHeight(), Image.SCALE_SMOOTH);
}
};
Image quality will degrade over time with the second solution, so it is recommended that you keep the original and the copy separate.
Create a class the extends JPanel. Have that class load the image by overriding paintComponent
class BackgroundPanel extends JPanel
{
Image img;
public BackgroundPanel()
{
// Read the image and place it in the variable img so it can be used in paintComponent
img = Toolkit.getDefaultToolkit().createImage("ABC0001.jpg");
}
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 0, null); // draw the image
}
}
Now that you have this class, simply add this to your JFrame (or whereever you want the background).
//create refrence if you want to add stuff ontop of the panel
private BackgroundPanel backGroundPanel;
//constructor
add(backGroundPanel, BorderLayout.CENTER);
The size of the background will fill the entire frame so no need to scale it unless you want it smaller

Categories

Resources