Background info : I have a JFrame with a gridlayout of (5,7) and am trying to add an image to the cell grid of (0,0)
I was following this guide on adding image to a specific JPanel .
To show a image in a JPanel cell:
- List item
- Put the chip image into an ImageIcon
- Put that ImageIcon into a JLabel via JLabel's setIcon(chipIcon) method
- Add the JLabel to the JPanel via the add(someLabel) method -- and the JPanel now will display the image.
Problem
The image is added to the JPanel but it seems the image is enlarged alot and then added to the JPanel .
Reality
Expectations
Compilable source code
package testing;
import java.io.*;
import java.util.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Testing extends JPanel
{
public static class TestPanel extends JPanel
{
TestPanel()
{
int i = 5; // num of rows
int j = 7; // num of cols
PanelHolder = new JPanel[i][j];
setLayout(new GridLayout(i,j));
for (int m=0 ; m<i;m++)
{
for(int n=0;n<j;n++)
{
PanelHolder[m][n] = new JPanel();
add(PanelHolder[m][n]);
}
}
ImageIcon ic1 = new ImageIcon("./src/testing/Ace_Diamond_1_1.png");
JLabel jl1 = new JLabel();
jl1.setIcon(ic1);
PanelHolder[0][0].add(jl1);
}
JPanel [][] PanelHolder;
JLabel DeckLabel;
JPanel DeckPanel;
ImageIcon Deckimg;
private BufferedImage image;
BufferedImage image2;
}
public static class ImagePanel extends JPanel
{
ImagePanel(BufferedImage image)
{
this.i = image;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(i,0,0, getWidth(), getHeight(), this);
}
BufferedImage i;
}
public static void main(String[] args)
{
TestPanel tp = new TestPanel();
JFrame frame = new JFrame();
frame.add(tp);
frame.pack();
frame.setVisible(true);
}
}
Download the image here
Note: For some unknown reason , you have to clean and rebuilt the solution for any changes you made else it will stick to the old code