Resizing Image in JPanel - java

I am tryimg to set an image as background in JPanel and resize it to desired size.
This is MyPanel where i choose image and set it as backgorund:
public class MyPanel extends JPanel {
Image img;
public MyPanel(LayoutManager l) {
super(l);
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String sname = file.getAbsolutePath();
img = new ImageIcon(sname).getImage();
double xRatio = img.getWidth(null) / 400;
double yRatio = img.getHeight(null) / 400;
double ratio = (xRatio + yRatio) / 2;
img = img.getScaledInstance((int)(img.getWidth(null) / ratio), (int)(img.getHeight(null) / ratio), Image.SCALE_SMOOTH);
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, Color.WHITE, null);
}
}
And this is my frame:
public class MyFrame extends JFrame {
public MyFrame () {
initUI();
}
private void initUI() {
MyPanel pnl = new MyPanel(null);
add(pnl);
setSize(600, 600);
setTitle("My component");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame ex = new MyFrame ();
ex.setVisible(true);
}
});
}
}
The problem is the image doesn't show at first. It shows when i for example change frame size a little.
Like that:

You are loading your image asynchronously.
The ImageIcon(String) constructor uses Toolkit.getImage internally, which is a hold-over from the 1990s, when many home Internet connections were so slow that it made sense to always load images in a background thread.
Since the image is loading in the background, img.getWidth(null) might return the image's size, or it might return -1. The documentation explains this.
So, how do you wait until the image has been loaded in that background thread?
Normally, you would observe the image's progress, using an ImageObserver. It just so happens that all AWT Components, and by extension, all Swing JComponents, implement ImageObserver. So you have an ImageObserver object: your MyPanel instance.
So, instead of passing null to all those methods, you would pass your MyPanel instance—that is, this:
double xRatio = img.getWidth(this) / 400;
double yRatio = img.getHeight(this) / 400;
And:
g.drawImage(img, 0, 0, Color.WHITE, this);
However… this will properly track the image's loading progress, but still doesn't guarantee that img.getWidth will return a positive value at the time that you call it.
To guarantee that an image is fully loaded immediately, you can replace the use of ImageIcon with ImageIO.read:
File file = fc.getSelectedFile();
try {
img = ImageIO.read(file);
} catch (IOException e) {
throw new RuntimeException("Could not load \"" + file + "\"", e);
}
This is different from using ImageIcon and Toolkit, because it doesn't just return an Image, it returns a BufferedImage, which is a type of Image that is guaranteed to be fully loaded and present in memory—no background loading to worry about.
Since a BufferedImage is already loaded, it has some additional methods which don't need an ImageObserver, in particular getWidth and getHeight methods which don't require an argument:
BufferedImage bufferedImg = (BufferedImage) img;
double xRatio = bufferedImg.getWidth() / 400.0;
double yRatio = bufferedImg.getHeight() / 400.0;
Notice I changed 400 to 400.0. This is because dividing one int by another int results in integer arithmetic in Java. For instance, 200 / 400 returns zero, because 200 and 400 are both int values. 5 / 2 produces the int value 2.
However, if either or both numbers are doubles, Java treats the entire thing as a double expression. So, (double) 200 / 400 returns 0.5. The presence of a decimal point in a sequence of digits indicates a double value, so 200.0 / 400 and 200 / 400.0 (and, of course, 200.0 / 400.0) will also return 0.5.
Finally, there is the issue of scaling. I recommend reading MadProgrammer's answer, and in particular, the java.net article to which his answer links, The Perils of Image.getScaledInstance().
The short version is that Image.getScaledInstance is another hold-over from the 1990s, and doesn't do a very good job of scaling. There are two better options:
Draw your image into a new image, and let the drawImage method handle the scaling, using the Graphics2D object's RenderingHints.
Use an AffineTransformOp on your image to create a new, scaled image.
Method 1:
BufferedImage scaledImage = new BufferedImage(
img.getColorModel(),
img.getRaster().createCompatibleWritableRaster(newWidth, newHeight),
false, new Properties());
Graphics g = scaledImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_SPEED);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.drawImage(img, 0, 0, newWidth, newHeight, null);
g.dispose();
Method 2:
RenderingHints hints = new RenderingHints();
hints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_SPEED);
hints.put(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
AffineTransform transform = AffineTransform.getScaleInstance(
(double) newWidth / img.getWidth(),
(double) newHeight / img.getHeight());
BufferedImageOp op = new AffineTransformOp(transform, hints);
BufferedImage scaledImage = op.filter(img, null);
You may want to alter the RenderingHints values, based on your own preferred trade-off of speed versus quality. They're all documented in the RenderingHints class.

You have to invoke setVisible(true):
public MyFrame () {
initUI();
setVisible(true);
}

Related

Get an image that's the difference between two images (Java Graphics2D)

Here's what I'm trying to do:
Get an image that's the difference between two images.
Context:
I have 2 images (identical) but one is bigger than the other.
I superimpose the smaller one in the center of the bigger one.
I would like to retrieve an image that is the difference between the 2 images.
Expected outcome:
What code would you propose to do that in an efficient way?
Edit :
I didn't specify the way.
I work in a Graphics2D context with BufferedImage
Thank a lot Camickr !
It was very simple so far.
Here is the result :
...
BufferedImage finalCut = extractEdge(source, dest);
...
g2d.drawImage(buff, 100, 100, null);
...
public static BufferedImage extractEdge(BufferedImage imgBottom, BufferedImage imgTop)
{
BufferedImage buffer = new BufferedImage(imgBottom.getWidth(), imgBottom.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2dBuff = buffer.createGraphics();
g2dBuff.setComposite(AlphaComposite.getInstance(AlphaComposite.XOR));
g2dBuff.drawImage(imgBottom, 0, 0, null);
g2dBuff.drawImage(imgTop, (int) getCenter(0, imgBottom.getWidth(), imgTop.getWidth(), true), (int) getCenter(0, imgBottom.getHeight(), imgTop.getHeight(), true), null);
return buffer;
}
public static float getCenter(float startZone, float zoneLenght, float elementLenght, boolean round)
{
float s = startZone + (zoneLenght - elementLenght) / 2f;
return (round) ? Math.round(s) : s;
}
Final cut

Scale images as a single surface in Java 2D API

There is a method called scale(double sx, double sy) in Graphics2D in Java. But this method seems like to scale images as separate surfaces rather than a single surface. As a result, scaled images have sharp corners if original images have no extra width and height. The following screenshot demonstrates the problem:
Here is the code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class TestJava {
static int scale = 10;
public static class Test extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.scale(scale, scale);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage img = null;
try {
img = ImageIO.read(new File("Sprite.png"));
} catch (IOException e) {
e.printStackTrace();
}
g2.drawImage(img, null, 5, 5);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Test test = new Test();
test.setBackground(Color.WHITE);
frame.add(test);
frame.setSize(300, 350);
frame.setVisible(true);
}
}
One possible solution to the problem is original images having extra width and height (in this case "Sprite.png"). But this does not seem to be a good way to eliminate the problem. So I am seeking for a programmatic way in Java to solve this problem rather than using an image editor. What is the way to do so?
In your example it's not the image you scale, but you set a scaling transformation on the Graphics2D object which will be applied on all operations performed on that graphics context.
If you want to scale an image, you have 2 options. All I write below uses java.awt.Image, but since BufferedImage extends Image, all this applies to BufferedImage as well.
1. Image.getScaledInstance()
You can use the Image.getScaledInstance(int width, int height, int hints) method. The 3rd parameter (the hints) tells what scaling algorithm you want to use which will affect the "quality" of the scaled image. Possible values are:
SCALE_DEFAULT, SCALE_FAST, SCALE_SMOOTH, SCALE_REPLICATE, SCALE_AREA_AVERAGING
Try the SCALE_AREA_AVERAGING and the SCALE_SMOOTH for nicer scaled images.
// Scaled 3 times:
Image img2 = img.getScaledInstance(img.getWidth(null)*3, img.getHeight(null)*3,
Image.SCALE_AREA_AVERAGING);
// Tip: you should cache the scaled image and not scale it in the paint() method!
// To draw it at x=100, y=200
g2.drawImage(img2, 100, 200, null);
2. Graphics.drawImage()
You can use different Graphics.drawImage() overloads where you can specify the size of the scaled image. You can "control" the image quality with the KEY_INTERPOLATION rendering hint. It has 3 possible values:
VALUE_INTERPOLATION_NEAREST_NEIGHBOR, VALUE_INTERPOLATION_BILINEAR,
VALUE_INTERPOLATION_BICUBIC
The VALUE_INTERPOLATION_BILINEAR uses a bilinear interpolation algorithm of the 4 nearest pixels. The VALUE_INTERPOLATION_BICUBIC uses a cubic interpolation of the 9 nearby pixels.
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
// To draw image scaled 3 times, x=100, y=200:
g2.drawImage(img, 100, 200, img.getWidth(null)*3, img.getHeight(null)*3, null);
Removing sharp edges
If you want to avoid sharp edges around the image, you should write a loop to go over the pixels at the edge of the image, and set some kind of transparency, e.g. alpha=0.5 (or alpha=128). You might also do this on multiple rows/columns, e.g. 0.8 alpha for the edge, 0.5 alpha for the 2nd line and 0.3 alpha for the 3rd line.
An interesting question (+1). I think that it is not trivial to find a good solution for this: The interpolation when scaling up the image always happens inside the image, and I can not imagine a way to make it blur the scaled pixels outside the image.
This leads to fairly simple solution: One could add a 1-pixel-margin around the whole image. In fact, this is the programmatic way of the solution that you proposed yourself. The resuld would look like this:
(the left one is the original, and the right one has the additional 1-pixel-border)
Here as a MCVE, based on your example
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ScaledPaint
{
static int scale = 10;
public static class Test extends JPanel
{
BufferedImage image = createTestImage();
BufferedImage imageWithMargin = addMargin(image);
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.scale(scale, scale);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.drawImage(image, 5, 5, null);
g2.drawImage(imageWithMargin, 30, 5, null);
}
}
private static BufferedImage createTestImage()
{
BufferedImage image =
new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.RED);
g.drawOval(0, 0, 19, 19);
g.dispose();
return image;
}
private static BufferedImage addMargin(BufferedImage image)
{
return addMargin(image, 1, 1, 1, 1);
}
private static BufferedImage addMargin(BufferedImage image,
int left, int right, int top, int bottom)
{
BufferedImage newImage =
new BufferedImage(
image.getWidth() + left + right,
image.getHeight() + top + bottom,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, left, top, null);
g.dispose();
return newImage;
}
private static BufferedImage convertToARGB(BufferedImage image)
{
BufferedImage newImage =
new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Test test = new Test();
test.setBackground(Color.WHITE);
frame.add(test);
frame.setSize(600, 350);
frame.setVisible(true);
}
}
But...
... one problem with this approach can already be seen in the screenshot: The image becomes larger. And you'll have to take this into account when painting the image. So if your original sprites all had a nice, predefined, easy-to-handle size like 16x32, they will afterwards have a size of 18x34, which is rather odd for a tile. This may not a problem, depending on how you are handling your tile sizes. But if it is a problem, one could think about possible solutions. One solution might be to ...
take the 16x32 input image
create a 16x32 output image
paint the 16x32 intput image into the region (1,1)-(15,31) of the output image
But considering the fact that in sprites of this size, every single pixel may be important, this may have undesirable effects as well...
An aside: Altough I assume that the code that you posted was only intended as a MCVE, I'd like to point out (for others who might read this question and the code) :
You shoud NOT load images in the paintComponent method
For efficient painting, any PNG that is loaded (particularly when it contains transparency) should be converted into an image with a known type. This can be done with the convertToARGB method in my code snippet.

Java image display issue

Dear wonderful people of stackoverflow
A group of my friends are attempting to make a level editor in Java.
We have a Jpanel instead of a Jframe and we are trying to put small images onto the Jpanel from a filepath saved as a string. In the end we want a list of images that you can just drop on. So far we have tried a few methods with no luck.
We can load the images, however we can't get these images to actually display, What would be the best means of solving said problem?
below is a sample of what we have so far.
EnemyPlacementGrid = new JPanel();
EnemyPlacementGrid.addMouseListener(new MouseAdapter() {
//#Override
public int mouseX;
public int mouseY;
public void mouseClicked(MouseEvent arg0) { //what happens when you click in the EnemyPlacementGrid
System.out.println("Correct Area for placement");
mouseX = arg0.getX();
mouseY = arg0.getY();
//System.out.println("X:" + mouseX + ", Y:" + mouseY );
Enemy newEnemy = workingEnemy.cloneSelf();
newEnemy.setLocation(mouseX, mouseY);
System.out.println("newEnemy object: " + newEnemy);
System.out.println(newEnemy.weaponList);
currentWave.addEnemy(newEnemy);
System.out.print(currentLevel);
}
});
Any and all help is greatly appreciated.
UPDATE:
As of now I have an image appearing, however I can't update said image. Note code below:
public void run() {
try {
BufferedImage img = ImageIO.read(new File(IMG_PATH));
ImageIcon icon = new ImageIcon(img);
WaveScreen frame = new WaveScreen();
JPanel panel = (JPanel)frame.getContentPane();
JLabel label = new JLabel();
label.setIcon(new ImageIcon("images/map_on.png"));// your image here
panel.add(label);
frame.setVisible(true);
panel.add(label);
panel.repaint();
} catch (Exception e) {
e.printStackTrace();
}
update, method tried from comments:
Graphics2D g = null;
Graphics2D g2 = (Graphics2D)g;
Image imageVariable = new ImageIcon("images/map_on.png").getImage();
g.drawImage(imageVariable, mouseX, mouseY, null);
Well, i'd say to try using Graphics, meaning you need to override the paint method; i'd recommend that you put the mouseX and mouseY as global variables though…
// creating global image variable for use later
Image imageVariable = new ImageIcon("image path").getImage();
public void paintComponent(Graphics g) {
// here you could either create a Graphics2D object
// Graphics2D g2 = (Graphics2D)g;
// or you could use the g parameter as it is, doesn't matter.
// use the global variable for the image to be drawn onto the screen
// use the global value of the mouseX and mouseY for where you click the mouse
// to place the image, and this should be it
g.drawImage(imageVariable, mouseX, mouseY, null);
}
Hope this helps!
If the game is simple, user2277872's solution will work and you can use graphics2D from java. However, if you are planning on a more sophisticated game (lots of interaction, lots of textures), then the default Java framework for 2D graphics will prove to be too slow.
If you are planning on such a game, I can highly recommend either learning OpenGL or using an existing framework for graphics, such as
JMonkeyEngine (http://jmonkeyengine.com/)
or
Slick (http://slick.cokeandcode.com/index.php)
More information: What should I use to display game graphics?

Creating a sized image out of a string in Java

I am making a 2d engine using Java based on entities. The physics and sprites are done, but I still need to be able to draw text with the BaseText class. For experimental purposes I am using the following code in the Renderer class (that handles drawing all the sprites and such):
BufferGraphics.drawString(((BaseText) Entity).getText(), (int) -(Origin.getX() * PositionTransform), (int) -Origin.getY());
I would like to, however, be able to either move this code into the setText(final String Text) method of the BaseText entity, i.e. when it is called a new image is created containing the text specified (possibly in different fonts and sizes and such, I haven't decided).
My problem is this: I would like to be able to resize (scale) the text to my liking. It would also be nice to have the text converted to an image as I can get the dimensions of it and set the size of the text entity itself.
Basically, what I need follows something along these lines:
Take desired string and feed it into the setText method.
Take the string and draw it onto an image, sized so that the text will fit into it exactly.
Set this new image to the Image field in the entity so that the engine can draw it.
Is this even possible? There may be a way to do this with the FontMetrics class or whatever it may be called, but I'm not so sure as I have not used it before.
Edit : Let me clarify: I want to create a BufferedImage based on the size of some text set to a specific font and size, not size the text to fit an image.
Edit 2: Thanks to this fellow Andrew, whom so graciously provided code, I was able to add some code to the engine that, by all means, just plain should work. Again, however, not even with that drawRect in there, the image either remains either transparent or somehow is not getting drawn. Let me supply some breadcrumbs: -snip-
The stupid thing is that all the other sprites and images and such draw fine, so I am not sure how it could be the Renderer.
By the way, that was the paint() method.
Edit 3:
...
Uh...
...
Oh my.
I am...
...
Text can not explain how hard I belted myself in the face with my left palm.
BaseText.java
#Override
public BufferedImage getImage() {return null;}
Renderer.java
BufferedImage Image = Entity.getImage();
I am
a huge idiot.
Thank you, Andrew, for that code. It worked fine.
Edit 4: By the way, here's the final code that I used:
public void setText(final String Text)
{
Graphics2D Draw = (Graphics2D) Game.View.getBuffer().getDrawGraphics();
FontMetrics Metrics = Draw.getFontMetrics();
Rectangle2D Bounds = Metrics.getStringBounds(Text, Draw);
BufferedImage NewImage = new BufferedImage((int) Bounds.getWidth(), (int) (Bounds.getHeight() + Metrics.getDescent()), BufferedImage.TYPE_INT_RGB);
Draw = (Graphics2D) NewImage.getGraphics();
Draw.setColor(new Color(0xAAFF0000));
Draw.drawRect(0, 0, NewImage.getWidth(), NewImage.getHeight());
Draw.drawString(Text, 0, (int) Bounds.getHeight());
this.Image = NewImage;
this.Text = Text;
this.setSize(new Vector(NewImage.getWidth(), NewImage.getHeight()));
}
Use FontMetrics, GlyphView or the preferred size a JLabel (handy for getting the size needed to display formatted text.
Adjust the sizes of the font in step 1 until it fits. Call BufferedImage.createGraphics() to get a Graphics2D object. Paint the String to that.
I do not understand point 3, so won't comment.
Here is how it would work with either FontMetrics or a JLabel.
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
class TextSize {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Technique 1 - FontMetrics
String s = "The quick brown fox jumps over the lazy dog!";
BufferedImage bi = new BufferedImage(
1,
1,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
FontMetrics fm = g.getFontMetrics();
Rectangle2D b = fm.getStringBounds(s,g);
System.out.println(b);
bi = new BufferedImage(
(int)b.getWidth(),
(int)(b.getHeight() + fm.getDescent()),
BufferedImage.TYPE_INT_RGB);
g = bi.getGraphics();
g.drawString(s,0,(int)b.getHeight());
JOptionPane.showMessageDialog(
null,
new JLabel(new ImageIcon(bi)));
// Technique 3 - JLabel
JLabel l = new JLabel(s);
l.setSize(l.getPreferredSize());
bi = new BufferedImage(
l.getWidth(),
l.getHeight(),
BufferedImage.TYPE_INT_RGB);
g = bi.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,400,100);
l.paint(g);
JOptionPane.showMessageDialog(
null,
new JLabel(new ImageIcon(bi)));
}
});
}
}

Move multiple BufferedImage in Java2D?

How can I mousedrag different BufferedImages in Java2D?
For instance, if I have ten or more images, how can I move that images which my mouse is over?
Now I'm importing an BufferedImage with
BufferedImage img = new BufferdImage(new File("filename"));
And I'm painting this with Graphics2D with
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2d = (Graphics2D) g;
g2d.drawImage(img, x1, y1, null);
g2d.drawImage(img2, x2, y2,null);
}
Everytime I'm moving on a image I'm repaint()-ing the entire screen.
My mousemove class is as follows
class MouseMotionHandler extends MouseMotionAdapter {
#Override
public void mouseDragged(MouseEvent e) {
x1 = e.getX() - (img.getWidth() / 2);
y1 = e.getY() - (img.getHeight() / 2);
repaint();
}
}
With this method I'm able to "drag" one picture, but what to do when I will drag more individually?
Use the BufferedImage to create an ImageIcon which you use to create a JLabel. Then you add the JLabel to the panel that uses a null layout. No custom painting code is required to do this.
Now if you want to drag the label around you can use the Component Mover.
You can try making a custom component that contains only a single image. Along with your painting and mouse motion handling code, the component overrides the contains method so that it returns true only if the coordinates are within the image.
These components are then stacked in a JLayeredPane, (hopefully) only moving the images that the mouse is on top of.
From what you ask I suppose that your current repainting logic is global. You need to apply it to every image you have. So, if you for instance display every image in JPanel attach MouseMotionListener to every such panel and make this logic happen in JPanel.
If you post more code - especially of the component you show your images in - I will be able to go into more details.
Here's is a simple example that implements dragging for either single- or multiple-selections. The object Node would correspond roughly to your object Card.
Addendum: Also considered the Overlap Layout mentioned in this answer to a related question. Instead of List<Node>, your program would manage a List<Card>, where each Card is a JLabel having a card image.
I should make tree arrays:
one for the x-values
one for the y-values
one for the BufferedImages
So, something like this:
int[] xValues = new int[10];
int[] yValues = new int[10];
BufferedImage[] imgs = new BufferedImage[10];
Then the
class MouseMotionHandler extends MouseMotionAdapter {
#Override
public void mouseDragged(MouseEvent e) {
for (int i = 0; i < 10; i++)
{
xValues[i] = e.getX() - (imgs[i].getWidth() / 2);
yValues[i] = e.getY() - (imgs[i].getHeight() / 2);
}
repaint();
}
}
Then paint them like this:
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2d = (Graphics2D) g;
for (int i = 0; i < 10; i++)
{
g2d.drawImage(imgs[i], xValues[i], yValues[i], null);
}
}
I think something like this is what you need.
Here's the code for my JLayeredPane init. My problem here is that my images don't show up...
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new java.awt.Dimension(500, 410));
layeredPane.setBorder(javax.swing.BorderFactory.createTitledBorder(
"Center deck"));
for(BufferedImage imgs : images){
JLabel label = new JLabel(new ImageIcon(imgs));
layeredPane.add(label, JLayeredPane.DEFAULT_LAYER);
}
add(layeredPane);

Categories

Resources