How would I add the backgroung image to my JPanel without creating a new class or method, but simply by inserting it along with the rest of the JPanel's attributes?
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class.
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
Here is an example of the method that sets my JPanel:
public static JPanel drawGamePanel(){
//Create game panel and attributes
JPanel gamePanel = new JPanel();
Image background = Toolkit.getDefaultToolkit().createImage("Background.png");
gamePanel.drawImage(background, 0, 0, null);
//Set Return
return gamePanel;
}
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
You can use other component which allows to add image as icon directly e.g. JLabel if you want.
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?
Simplest way to set image as JPanel background
Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.
See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:
scaled
tiled
actual
As I know the way you can do it is to override paintComponent method that demands to inherit JPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint the background image and scale it to fill the entire space
g.drawImage(/*....*/);
}
The other way (a bit complicated) to create second custom JPanel and put is as background for your main
ImagePanel
public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;
public ImagePanel(Image image)
{
this.image = image;
this.iWidth2 = image.getWidth(this)/2;
this.iHeight2 = image.getHeight(this)/2;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
int x = this.getParent().getWidth()/2 - iWidth2;
int y = this.getParent().getHeight()/2 - iHeight2;
g.drawImage(image,x,y,this);
}
}
}
EmptyPanel
public class EmptyPanel extends JPanel{
private static final long serialVersionUID = 1L;
public EmptyPanel() {
super();
init();
}
#Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
public void init(){
LayoutManager overlay = new OverlayLayout(this);
this.setLayout(overlay);
ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
iPanel.setLayout(new BorderLayout());
this.add(iPanel);
iPanel.setOpaque(false);
}
}
IconToImage
public class IconToImage {
Icon icon;
Image image;
public IconToImage(Icon icon) {
this.icon = icon;
image = iconToImage();
}
public Image iconToImage() {
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
/**
* #return the image
*/
public Image getImage() {
return image;
}
}
Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
public class BackgroundImageApp {
private JFrame frame;
private BackgroundImageApp create() {
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private void show() {
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Component createContent() {
final Image image = requestImage();
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
JButton button = new JButton(label);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createRigidArea(new Dimension(15, 15)));
panel.add(button);
}
panel.setPreferredSize(new Dimension(500, 500));
return panel;
}
private Image requestImage() {
Image image = null;
try {
image = ImageIO.read(new URL("http://www.johnlennon.com/wp-content/themes/jl/images/home-gallery/2.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new BackgroundImageApp().create().show();
}
});
}
}
class Logo extends JPanel
{
Logo()
{
//code
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon img = new ImageIcon("logo.jpg");
g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
}
}
INITIALIZE YOUR JPANEL AS BELOW. NOTE THE MISSING SEMICOLON.. INSTEAD OPEN A CURLY BRACE THEN OVERRIDE THAT METHOD.. THIS WAY YOU DON'T HAVE TO EXTEND TO ANYTHING
ImageIcon img = new ImageIcon("background.jpg");
JPanel panel1 = new JPanel()
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img.getImage(), 0, 0, null);
}
};
public demo1() {
initComponents();
ImageIcon img = new ImageIcon("C:\\Users\\AMIT TIWARI\\Documents\\NetBeansProjects\\try\\src\\com\\dd.jpeg"); //full path of image
Image img2 = img.getImage().getScaledInstance(mylabel.getWidth(), mylabel.getHeight(),1);
ImageIcon img3 = new ImageIcon(img2);
mylabel.setIcon(img3);
}
Related
I'm trying to make my program object oriented and I'm attempting to split it into several classes. The short version is that I want to paint different objects in 1 JFrame. So I created a class per object that I wanted to paint, defined the object in my method and then add them to my frame. The problem is that only the last component is painted in the frame. I tried adding the objects to a JPanel first but that doesn't seem to work.
trees1
public class trees1 extends JComponent{
public final ImageIcon pokemontree;
public trees1(){
ImageIcon poke = new ImageIcon("pokemontree.png");
Image image = poke.getImage(); // transform it
pokemontree = new ImageIcon(newimg); // transform it back
}
public void paintComponent (Graphics g){
Graphics2D g2 = (Graphics2D) g;
pokemontree.paintIcon(this,g2 , 100,200);
}
}
testing
// main program
public class testing {
public static void main(String[] args){
JFrame win = new JFrame();
win.setSize(600,400);
win.setTitle("Test");
win.setResizable(false);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trees1 exo = new trees1();
Playerwalking p1 = new Playerwalking(1,2);
win.add(exo);
win.add(p1);
win.setVisible(true);
}
JFrame content pane default uses BorderLayout
The default content pane will have a BorderLayout.
For BorderLayout, the "add()" method always set to "CENTER" if you don't specify the location (NORTH/EAST/SOUTH/WEST/CENTER etc) of the components you adding.
You need to specify your "getPreferredSize()" in your component, also understand how to use the BorderLayout (or other layout manager properly).
public class Test1 extends JFrame {
public static void main(String[] args) throws Exception {
JFrame win = new JFrame();
win.setSize(600,400);
win.setTitle("Test");
win.setResizable(false);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.add(new trees1(), BorderLayout.CENTER);
win.add(new trees1(), BorderLayout.SOUTH);
win.add(new trees1(), BorderLayout.EAST);
win.pack();
win.setVisible(true);
}
}
class trees1 extends JComponent {
public final ImageIcon pokemontree;
public trees1(){
ImageIcon poke = new ImageIcon("c:\\temp\\2.png");
Image image = poke.getImage(); // transform it
pokemontree = new ImageIcon(image); // transform it back
}
#Override
public Dimension getPreferredSize() {
return new Dimension(pokemontree.getIconWidth(), pokemontree.getIconHeight());
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
pokemontree.paintIcon(this,g2 , 0,0);
}
}
i am setting frame's background image when i run program my other components are invisible only image is visible in frame
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
In the main class I call the above class as shown below:
BufferedImage myImage = ImageIO.read(new File("cal.jpg"));
frame.setContentPane(new ImagePanel(myImage));
You have this code:
BufferedImage myImage = ImageIO.read(new File("cal.jpg"));
frame.setContentPane(new ImagePanel(myImage));
but you appear to be creating the ImagePanel instance inline, and don't appear to be adding any components to this ImagePanel instance, so I'm not surprised that you're not seeing any components. You also don't seem to be adding any components to it in the ImagePanel constructor.
Consider adding components to the ImagePanel class within its constructor, or in the class that uses it, create an ImagePanel instance, assign it to a variable, add components to it, and then place it into the JFrame's contentPane.
Side recommendations:
Consider getting your image as a Jar resource and not as a File, since likely you will Jar the classes at some point, and if you continue using File, your image might not be reachable.
Make sure to give your ImagePanel a decent layout manager. I believe that JComponents use null layouts by default, something that you don't want to use.
For example, this worked for me:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestImagePanel {
private static void createAndShowGui() {
String resource = "/imgFolder/PlanetEarth.jpg";
Image image = null;
try {
image = ImageIO.read(TestImagePanel.class.getResource(resource));
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
ImagePanel mainPanel = new ImagePanel(image);
mainPanel.setLayout(new FlowLayout());
mainPanel.add(new JButton("Fubars Rule!"));
JFrame frame = new JFrame("TestImagePanel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ImagePanel extends JComponent {
private Image image;
public ImagePanel(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
int w = image == null ? superSize.width : Math.max(superSize.width, image.getWidth(null));
int h = image == null ? superSize.height : Math.max(superSize.height, image.getHeight(null));
Dimension d = new Dimension(w, h);
return d;
}
}
and showed this GUI:
How would I add the backgroung image to my JPanel without creating a new class or method, but simply by inserting it along with the rest of the JPanel's attributes?
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class.
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
Here is an example of the method that sets my JPanel:
public static JPanel drawGamePanel(){
//Create game panel and attributes
JPanel gamePanel = new JPanel();
Image background = Toolkit.getDefaultToolkit().createImage("Background.png");
gamePanel.drawImage(background, 0, 0, null);
//Set Return
return gamePanel;
}
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
You can use other component which allows to add image as icon directly e.g. JLabel if you want.
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?
Simplest way to set image as JPanel background
Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.
See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:
scaled
tiled
actual
As I know the way you can do it is to override paintComponent method that demands to inherit JPanel
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint the background image and scale it to fill the entire space
g.drawImage(/*....*/);
}
The other way (a bit complicated) to create second custom JPanel and put is as background for your main
ImagePanel
public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;
public ImagePanel(Image image)
{
this.image = image;
this.iWidth2 = image.getWidth(this)/2;
this.iHeight2 = image.getHeight(this)/2;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
int x = this.getParent().getWidth()/2 - iWidth2;
int y = this.getParent().getHeight()/2 - iHeight2;
g.drawImage(image,x,y,this);
}
}
}
EmptyPanel
public class EmptyPanel extends JPanel{
private static final long serialVersionUID = 1L;
public EmptyPanel() {
super();
init();
}
#Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
public void init(){
LayoutManager overlay = new OverlayLayout(this);
this.setLayout(overlay);
ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
iPanel.setLayout(new BorderLayout());
this.add(iPanel);
iPanel.setOpaque(false);
}
}
IconToImage
public class IconToImage {
Icon icon;
Image image;
public IconToImage(Icon icon) {
this.icon = icon;
image = iconToImage();
}
public Image iconToImage() {
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
/**
* #return the image
*/
public Image getImage() {
return image;
}
}
Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
public class BackgroundImageApp {
private JFrame frame;
private BackgroundImageApp create() {
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private void show() {
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Component createContent() {
final Image image = requestImage();
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
JButton button = new JButton(label);
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createRigidArea(new Dimension(15, 15)));
panel.add(button);
}
panel.setPreferredSize(new Dimension(500, 500));
return panel;
}
private Image requestImage() {
Image image = null;
try {
image = ImageIO.read(new URL("http://www.johnlennon.com/wp-content/themes/jl/images/home-gallery/2.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new BackgroundImageApp().create().show();
}
});
}
}
class Logo extends JPanel
{
Logo()
{
//code
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon img = new ImageIcon("logo.jpg");
g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
}
}
INITIALIZE YOUR JPANEL AS BELOW. NOTE THE MISSING SEMICOLON.. INSTEAD OPEN A CURLY BRACE THEN OVERRIDE THAT METHOD.. THIS WAY YOU DON'T HAVE TO EXTEND TO ANYTHING
ImageIcon img = new ImageIcon("background.jpg");
JPanel panel1 = new JPanel()
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img.getImage(), 0, 0, null);
}
};
public demo1() {
initComponents();
ImageIcon img = new ImageIcon("C:\\Users\\AMIT TIWARI\\Documents\\NetBeansProjects\\try\\src\\com\\dd.jpeg"); //full path of image
Image img2 = img.getImage().getScaledInstance(mylabel.getWidth(), mylabel.getHeight(),1);
ImageIcon img3 = new ImageIcon(img2);
mylabel.setIcon(img3);
}
I am trying to program a board game. I want to load an image of the game board and then load a transparent grid over it. I wrote a custom panel to draw the image and added it to a layered panel as level 0. Then I make a JPanel with a GridLayout and added it at level 1. The layered pane is then put into a scroll pane to account for the background image being kinda large. The hope is to have most of the grid be transparent at any given time but if a player piece enters a square then I will set that square to be a color representing the piece. However when I set the top panel to transparent (by making a call to setOpaque(false)) I just get a white background, no image is present. Why is this?
public class ImagePanel extends JPanel
{
private Image image;
public ImagePanel(Image image)
{
this.image = image;
this.setPreferredSize(new Dimension(936,889));
}
protected void paintComponent(Graphics g)
{
g.drawImage(image, 0, 0, null);
}
}
Here is the code in the main program which creates the panels and nests them. backBoard is the outer frame. It is setVisible later on so that's not an issue.
BufferedImage boardImage = null;
try
{
boardImage = ImageIO.read(new File("Clue Board.jpg"));
}
catch(IOException e)
{
}
ImagePanel background = new ImagePanel(boardImage); //load clue board image
JPanel gameBoard = new JPanel (new GridLayout(24,24)); //yet to add actual squares
gameBoard.setSize(936,889);
gameBoard.setOpaque(false);
JLayeredPane lPane = new JLayeredPane();
lPane.setPreferredSize(new Dimension(936,889));
lPane.add(background, new Integer(0));
lPane.add(gameBoard, new Integer(1));
JScrollPane layerScroller = new JScrollPane(lPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
backBoard.add(layerScroller, BorderLayout.CENTER);
Try calling super.paintComponent(..) like so:
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
Dont call JFrame#setSize(..) use an appropriate LayoutManager and override getPrefferedSize(..) of JPanel which will return the correct size and then call pack() on JFrame instance before setting it visible.
Here is an example of how your ImagePanel class should look:
public class ImagePanel extends JPanel
{
private int width,height;
private Image image;
public ImagePanel(Image image)
{
this.image = image;
//so we can set the JPanel preferred size to the image width and height
ImageIcon ii = new ImageIcon(this.image);
width = ii.getIconWidth();
height = ii.getIconHeight();
}
//so our panel is the same size as image
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
I'm working through some simple applications to get familiar with Swing and running into problems.
I'm attempting to have a frame containing an image (in a panel) along with buttons to zoom in/out from the image.
I have been able to make a frame with the added image work fine (albeit with some frame sizing issues, but that is another story), however, when I call the same component class to add it to a panel, nothing appears. I'm hoping one of you can help shed light on the situation.
CODE:
Image Frame - Is working as shown
class ImageFrame extends JFrame{
public ImageFrame(){
setTitle("Java Image Machine");
init();
pack();
}
public final void init(){
//ZoomPanel zoomPanel = new ZoomPanel();
//ImagePanel imagePanel = new ImagePanel();
ImageComponent component = new ImageComponent();
//this.add(zoomPanel, BorderLayout.CENTER);
this.add(component);
//this.add(imagePanel, BorderLayout.SOUTH);
}
}
However, using the ImagePanel or adding the ZoomPanel simultaneously with the direct ImageComponent call, does not:
class ImagePanel extends JPanel{
public ImagePanel(){
//setBorder(BorderFactory.createLineBorder(Color.black));
ImageComponent component = new ImageComponent();
add(component);
}
}
Component class:
class ImageComponent extends JComponent{
public ImageComponent(){
try{
image = ImageIO.read(new File("test1.bmp"));
}
catch ( IOException e ){
e.printStackTrace();
}
System.out.println("W: " + image.getWidth(this) + " H: " + image.getHeight(this));
}
public void paintComponent( Graphics g ){
super.paintComponent(g);
if (image == null)
return;
width = image.getWidth(this);
height = image.getHeight(this);
//System.out.println("Image should be painted");
g.drawImage(image, 0, 0, null);
}
private Image image;
public int width;
public int height;
}
It works fine for me ( I just tested the ImageComponent class):
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Test {
/**
* Default constructor Test.class
*/
public Test() {
initComponents();
}
public static void main(String[] args) {
/**
* Create GUI and components on Event-Dispatch-Thread
*/
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
}
});
}
/**
* Initialize GUI and components (including ActionListeners etc)
*/
private void initComponents() {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add ImageComponent to JFrame instance
jFrame.add(new ImageComponent());
//pack frame (size JFrame to match preferred sizes of added components and set visible
jFrame.pack();
jFrame.setVisible(true);
}
}
class ImageComponent extends JComponent {
private Image image;
public int width;
public int height;
public ImageComponent() {
try {
image = ImageUtils.scaleImage(300, 300, ImageIO.read(new URL("http://harmful.cat-v.org/software/_java/java-evil-edition.png")));
//image = ImageIO.read(new URL("http://harmful.cat-v.org/software/_java/java-evil-edition.png"));//uses images scale
} catch (Exception e) {
e.printStackTrace();
}
//so we can set the JPanel preferred size to the image width and height
ImageIcon ii = new ImageIcon(image);
width = ii.getIconWidth();
height = ii.getIconHeight();
}
//so our panel is the same size as image
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null) {
return;
}
width = image.getWidth(this);
height = image.getHeight(this);
g.drawImage(image, 0, 0, null);
}
}
//class used for scaling images
class ImageUtils {
static Image scaleImage(int width, int height, BufferedImage filename) {
BufferedImage bi;
try {
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(filename, 0, 0, width, height, null);
} catch (Exception e) {
return null;
}
return bi;
}
}
problem might be the path to your file, or the fact that JPanel width and height will not be the same as the pictures thus we override getPrefferedSize(...) of JPanel and return correct size according to Image
Have you tried adding repaint() calls after adding the appropriate components in?
i.e.
class ImagePanel extends JPanel{
public ImagePanel(){
//setBorder(BorderFactory.createLineBorder(Color.black));
ImageComponent component = new ImageComponent();
add(component);
repaint();
}
}
Also double check that you are adding the ImagePanel (containing the ImageComponent) to the ImageFrame, and calling .setVisible(True).