Setting location for objects/images on a background - java

I'm currently working on a version of the game Ludo/Dude don't get mad, I've ran into a few problems one of the bigger ones being the fact that I cannot place the tokens where I want them to be. I need to set the tokens in certain positions for the start and will need a method with which I will calculate where to move them on the screen here is the code:
public class Ludo extends JFrame{
private BackgroundPanel imagePanel=null;
private JLabel jlTokenBlue1=null;
private JLabel jlTokenBlue2=null;
...
public Ludo(){
try{
//Creating background panel
imagePanel = new BackgroundPanel("ludoBoard.png");
add(imagePanel);
//create tokens for play
BufferedImage imageTokenBlue1 = ImageIO.read(new File("blue1.png"));
jlTokenBlue1 = new JLabel(new ImageIcon(imageTokenBlue1));
BufferedImage imageTokenBlue2 = ImageIO.read(new File("blue2.png"));
jlTokenBlue2 = new JLabel(new ImageIcon(imageTokenBlue2));
BufferedImage imageTokenBlue3 = ImageIO.read(new File("blue3.png"));
jlTokenBlue3 = new JLabel(new ImageIcon(imageTokenBlue3));
BufferedImage imageTokenBlue4 = ImageIO.read(new File("blue4.png"));
jlTokenBlue4 = new JLabel(new ImageIcon(imageTokenBlue4));
BufferedImage imageTokenRed1 = ImageIO.read(new File("red1.png"));
jlTokenRed1 = new JLabel(new ImageIcon(imageTokenRed1));
BufferedImage imageTokenRed2 = ImageIO.read(new File("red2.png"));
jlTokenRed2 = new JLabel(new ImageIcon(imageTokenRed2));
BufferedImage imageTokenRed3 = ImageIO.read(new File("red3.png"));
jlTokenRed3 = new JLabel(new ImageIcon(imageTokenRed3));
BufferedImage imageTokenRed4 = ImageIO.read(new File("red4.png"));
jlTokenRed4 = new JLabel(new ImageIcon(imageTokenRed4));
imagePanel.add(jlTokenBlue1);
imagePanel.add(jlTokenBlue2);
imagePanel.add(jlTokenBlue3);
imagePanel.add(jlTokenBlue4);
imagePanel.add(jlTokenRed1);
imagePanel.add(jlTokenRed2);
imagePanel.add(jlTokenRed3);
imagePanel.add(jlTokenRed4);
jlTokenRed1.setLocation(250,500);
}//End of try
catch(IOException ioe){
System.out.println("The background image cannot be loaded...");
}catch(NullPointerException npe){
npe.getMessage();
}
.
.
.
class BackgroundPanel extends JPanel
{
Image image;
public BackgroundPanel(String imageName)
{
try
{
image = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource(imageName), imageName));
}
catch (Exception e) { /*handled in paintComponent()*/ }
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}
I've tried using setLocation and repaint but was unable to set the tokens to be placed where I want them to be. I'd like to place the tokens into the white fields in their respective colors any help and/or suggestion is greatly appreciated. Below is a picture of how it looks right now.
Here is the link to the drive containing everything if you wish to check the files your self. drive.google.com/open?id=1xap_xz2K3SF37XQfRN3Y_LHoTHg0HNox
!

I've started some code for your game. You'll have to complete the code.
Here's the GUI I created.
The first thing I did was to employ a model / view / controller pattern. By separating the logical functions of the game, I could concentrate on one part at a time.
Here's the model I created. It's not complete, but I think you can see what I'm trying to do herd. I put his class in its own model package.
package com.ggl.ludo.model;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LudoModel {
private final BufferedImage gameBoard;
private final BufferedImage[] imageTokenBlue;
public LudoModel() {
imageTokenBlue = new BufferedImage[4];
imageTokenBlue[0] = getImage("blue1.png");
imageTokenBlue[1] = getImage("blue2.png");
imageTokenBlue[2] = getImage("blue3.png");
imageTokenBlue[3] = getImage("blue4.png");
gameBoard = getImage("ludoBoard.png");
}
public BufferedImage getGameBoard() {
return gameBoard;
}
public BufferedImage[] getImageTokenBlue() {
return imageTokenBlue;
}
private BufferedImage getImage(String fileName) {
try {
return ImageIO.read(getClass().getResourceAsStream("/" + fileName));
} catch (IOException e) {
return null;
}
}
}
All this code does is read in the images, and eventually, create the logical model of your game. It's not concerned with the view or the controller code at all.
The next class I created was the DrawingPanel class. This class draws the game board and eventually, draws the pieces on the board. The location of the pieces information goes into the model.
package com.ggl.ludo.view;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
import com.ggl.ludo.model.LudoModel;
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
private LudoFrame frame;
private LudoModel model;
public DrawingPanel(LudoFrame frame, LudoModel model) {
this.frame = frame;
this.model = model;
int width = model.getGameBoard().getWidth();
int height = model.getGameBoard().getHeight();
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(model.getGameBoard(), 0, 0, this);
// Your piece drawing code goes here
}
}
Next, I created a class to hold the JFrame. The JScrollPane code can be removed. My old laptop can't display a game board as large as yours. Something to keep in mind if you want others to play this game.
I put the menu code in its own method. I like to keep separate things separate. My feeble mind can't handle too many processes at one time.
package com.ggl.ludo.view;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import com.ggl.ludo.model.LudoModel;
public class LudoFrame {
private DrawingPanel drawingPanel;
private LudoModel ludoModel;
public LudoFrame(LudoModel ludoModel) {
this.ludoModel = ludoModel;
generateGUIControl();
}
private void generateGUIControl() {
JFrame frame = new JFrame("Ludo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenu());
drawingPanel = new DrawingPanel(this, ludoModel);
JScrollPane scrollPane = new JScrollPane(drawingPanel);
scrollPane.setPreferredSize(new Dimension(400, 400));
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenu() {
JMenuBar ludoMenuBar = new JMenuBar();
JMenu ludoMenuFirst = new JMenu("Information");
ludoMenuBar.add(ludoMenuFirst);
JMenuItem jmiDescription = new JMenuItem("Description");
JMenuItem jmiHelp = new JMenuItem("Help");
JMenuItem jmiRestart = new JMenuItem("Restart");
JMenuItem jmiExit = new JMenuItem("Exit");
ludoMenuFirst.add(jmiDescription);
ludoMenuFirst.add(jmiHelp);
ludoMenuFirst.add(jmiRestart);
ludoMenuFirst.add(jmiExit);
ludoMenuBar.add(ludoMenuFirst);
return ludoMenuBar;
}
}
Finally, the driver class that starts the whole process. You must start a Swing application on the Event Dispatch Thread(EDT). The call to SwingUtilities invokeLater ensures that your application starts on the EDT.
package com.ggl.ludo;
import javax.swing.SwingUtilities;
import com.ggl.ludo.model.LudoModel;
import com.ggl.ludo.view.LudoFrame;
public class Ludo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Ludo());
}
#Override
public void run() {
new LudoFrame(new LudoModel());
}
}
I hope this has been helpful to you. As far as the controllers, I suggest that you use a mouse listener and draw the game pieces on the game board.
Remember, information about the game piece locations goes into the model. The view drawing code draws from the information in the model.

Related

How would I add an action Listener to the button to refresh the image? [duplicate]

I have been trying to figure this out why not the next picture showing on the same panel after click the button. I want to separate those classes not into one class and used repaint() to re-invoke paintComponent() with the new pic.
Please help me. I am almost dying :(
when I run this, the first picture appears well. when the button is clicked to change the first picture to the second one, the Panel just keep on showing the first picture.
Thank you.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
class drawImage extends JPanel {
BufferedImage[] b = new BufferedImage[2];
public drawImage() {
try {
b[0] = ImageIO.read(new File("img/gameOn.png"));
b[1] = ImageIO.read(new File("img/gameOff.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(b[0], 0, 0, null);
}
public void setNextImage(BufferedImage image) {
b[0] = image;
repaint();
}
public BufferedImage getB0() {
return b[0];
}
public BufferedImage getB1() {
return b[1];
}
}// end drawImage
class clickedListener implements ActionListener {
BufferedImage pre = new drawImage().getB0();
BufferedImage next = new drawImage().getB1();
#Override
public void actionPerformed(ActionEvent e) {
new drawImage().setNextImage(next);
}
}
public class buttonFrame {
public static void main(String[] args) throws IOException {
JFrame jf = new JFrame("Button & Frame");
JButton btn = new JButton("Click");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.setLayout(new GridLayout(2, 0));
jf.add(new drawImage());
jf.add(btn);
jf.setSize(200, 250);
btn.addActionListener(new clickedListener());
}
}
Why not change your approach and make use of a JLabel instead? Set your image as an icon on the label and add it to your JPanel:
BufferedImage image = ImageIO.read(new File("image-path"));
JLabel label = new JLabel(new ImageIcon(image));
panel.add(label);
You can then make subsequent calls to JLabel#setIcon(...) each time you want the image to change.
You can also use ImageIcon like this
image = new ImageIcon(imageList[1]);
and when each time button is clicked you can change image like this
label.setIcon(image);

How do I add a button to Canvas without letting the button resize?

I'm working on a login screen for my game. I have a total of two images on it. One is a splash screenshot and the other is the background image. I'm using BufferedImages to render the images to the screen.
The problem I get is that when I add a standard button to the Canvas, the button takes up the whole window, and evidently, I don't want that.
I would post a picture, but alas, I do not have "enough reputation" to do that. Here's a look at my code though:
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.TextField;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class Login extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 495;
private static final int HEIGHT = 307;
private static final int SCALE = 2;
private final Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
public int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
private BufferedImage splash = new BufferedImage(315, 177, BufferedImage.TYPE_INT_RGB);
public int[] splashPixels = ((DataBufferInt) splash.getRaster().getDataBuffer()).getData();
private Thread thread;
public static boolean isRunning = false;
JFrame frame;
MainMenu menu;
Splash splashscreen;
Button login;
Button register;
TextField username;
private Login() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exc) {
exc.printStackTrace();
}
frame = new JFrame("Game Login");
menu = new MainMenu(WIDTH, HEIGHT, "/login/login_screen.png");
splashscreen = new Splash(315, 177, "/login/splash.png");
frame.setSize(size);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
setPreferredSize(size);
frame.add(this);
login = new Button("Login");
login.setBounds(0, 0, getWidth(), getHeight());
frame.add(login);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void begin() {
createBufferStrategy(2);
thread = new Thread(this);
thread.start();
isRunning = true;
}
private void finish() throws InterruptedException {
isRunning = false;
thread.join();
}
private void updateLogin() {
for (int a = 0; a < pixels.length; a++) {
pixels[a] = menu.pixels[a];
}
}
private void renderLogin() {
BufferStrategy buffer = getBufferStrategy();
Graphics gfx = buffer.getDrawGraphics();
for (int a = 0; a < splashPixels.length; a++) {
splashPixels[a] = splashscreen.splashPixels[a];
}
gfx.drawImage(image, 0, 0, getWidth(), getHeight(), null);
gfx.drawImage(splash, 320, 37, 625, 340, null);
gfx.setColor(Color.WHITE);
gfx.drawString("Game Co © 2013", 3, (getHeight() - 4));
gfx.drawString("\"Game\" is a trademark of Blah-Blah-Blah.", (getWidth() - 268), (getHeight() - 3));
gfx.dispose();
buffer.show();
}
public void run() {
while (isRunning == true) {
updateLogin();
renderLogin();
}
try {
finish();
} catch (InterruptedException exc) {
exc.printStackTrace();
}
}
public static void main(String[] args) {
Login login = new Login();
login.begin();
}
}
Once again, my only problem is that I keep getting a enlarged button.
Thanks in advance, I know you guys are busy and whatnot and I appreciate taking the time to look over and help answer my questions.
P.S. Does anyone know how to make a password field with AWT? I'll also need that too. ;)
Solution: add your JButton (again use Swing components) First to a JPanel (which uses FlowLayout by default), and then add that to the top level window.
You could just change the layout manager for your frame to a FlowLayout so it will behave like a JPanel.
frame.setLayout(new FlowLayout());
You state:
The problem I get is that when I add a standard button to the Canvas, the button takes up the whole window, and evidently, I don't want that.
You're trying to add a component directly to a container that is using BorderLayout, likely the contentPane of a top-level window, and so by default it is added BorderLayout.CENTER and fills the container.
Solution: add your JButton (again use Swing components) First to a JPanel (which uses FlowLayout by default), and then add that to the top level window.
Again, there's no need to mix AWT and Swing components and there are in fact strong arguments not to do so. I suggest that you stick with all Swing components for your GUI.
Does anyone know how to make a password field with AWT? I'll also need that too. ;)
Again, don't use AWT but instead use a Swing JPasswordField.

Java2D and Swing Not Outputing Images with JFrames and JPanels

I am working on the basics of a graphics program in swing and java2D to practice. I am having a problem wherein I cannot show my images. I have divided my code into 4 classes so that when the program gets larger it's easier to manage.
The idea is that I have very little in the Main, that Frame initializes my first screen, that the screens can all be subdivided into their own classes, TitleScreen being one of these, and PullImage does all of the work of buffering and printing images which bothered me.
When I run this I get an empty window and no errors, so I cannot figure out where the problem is.
Please and Thank you for your help.
Main
package com.game.pack;
import javax.swing.JFrame;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public final static void main(String[] args)
{
new Frame().initialize();
new TitleScreen().openScreen();
}
}
Frame
package com.game.pack;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame extends JFrame{
private static final long serialVersionUID = 1L;
public final void initialize()
{
JFrame frame = new JFrame("Game");
JPanel panel = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
panel.setSize(800,600);
frame.setLayout(null);
panel.setLayout(null);
frame.setLocationRelativeTo(null);
this.getContentPane().add(panel);
panel.setVisible(true);
frame.setVisible(true);
}
public final void close()
{
dispose();
}
}
TitleScreen
package com.game.pack;
public class TitleScreen {
public void openScreen()
{
new PullImage().printARGB("icons/titleBG.png",800,600,0,0);
new PullImage().printARGBFromSheet("icons/titleButtons.png",
200, 125, 400, 200, 200, 40, 0, 0);
while (1!=2)
{
}
PullImage
package com.game.pack;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
public class PullImage {
public void printARGB(String source, int sizeX, int sizeY, int locX, int locY)
{
Image Icon = new ImageIcon(source).getImage();
BufferedImage BuffedImage = new BufferedImage(sizeX, sizeY, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = BuffedImage.getGraphics();
graphics.drawImage(Icon,locX,locY,null);
}
public void printARGBFromSheet(String source, int sizeX, int sizeY, int locX, int locY, int width, int height, int sheetLocX, int sheetLocY)
{
Image Icon = new ImageIcon(source).getImage();
BufferedImage BuffedImage = new BufferedImage(sizeX,sizeY,BufferedImage.TYPE_INT_ARGB);
Graphics graphics = BuffedImage.getGraphics();
graphics.drawImage(Icon, locX, locY, locX+width, locY+height, sheetLocX, sheetLocY, sheetLocX+width, sheetLocY+height, null);
}
}
One problem lies here:
public final void initialize()
{
this.getContentPane().add(panel);
}
This is setting the content pane of your frame to the panel, not the JFrame you created. Essentially you're not adding it to the actual visible window. Just replace it with
frame.getContentPane().add(panel);

How do I order two components in a JFrame in order for transparency and ActionListeners to work?

When adding two components to a JFrame, where one sits inside another, If I add them in the order, Fullscreen Object, then JPanel, the JPanel displays correctly, but is essentially invisible, i.e it's action listener won't work and the clicks register on the fullscreen object. If I add them the other way round The JPanel works as it should, but doesn't display correctly (It has transparent areas).
This is the code for the Frame I am adding the components to.
gameOBJ = new gameClass(width, height);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(0);
frame.add(gameOBJ.UIPanel);
frame.add(gameOBJ);
frame.validate();
frame.setUndecorated(true);
frame.setBounds(0, 0, width, height);
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
new exitWindow("Don't forget to save your game! \n Are you sure you want to Exit?", true);
}
});
frame.setVisible(true);
gameOBJ.start();
Here is the code for the JPanel (Stripped down for simplicity's sake)
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
public class UserInterface extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private Image image;
private int xBound = 800;
private int yBound = 177;
private JButton mainMenuButton = new JButton(new ImageIcon("res/images/MainMenuButton.gif"));
private int buttonWidth = 179;
private int buttonHeight = 52;
public UserInterface()
{
this.setLayout(null);
this.image = new ImageIcon("res/images/UIPanelImage.gif").getImage();
this.setOpaque(false);
this.setSize(this.xBound, this.yBound);
mainThreeButtons(); //ONLY ONE SHOWN FOR SIMPLICITY
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, this); //IMAGE CONTAINS TRANSPARENCY
}
#Override
public void actionPerformed(ActionEvent event)
{
else if (event.getSource() == mainMenuButton)
{
new mainMenuWindow();
}
}
private void mainThreeButtons()
{
this.add(mainMenuButton);
mainMenuButton.addActionListener(this);
//mainMenuButton.setOpaque(false);
mainMenuButton.setBorderPainted(false);
mainMenuButton.setContentAreaFilled(false);
mainMenuButton.setBounds(617, 6, buttonWidth, buttonHeight);
}
}
I would show an image but I'm not allowed to, The area which is meant to be transparent isn't showing the frame, because it is grey, whatever I set as the Frame's background, OR the panel's background, as again it is grey whatever I set the panel's background colour as.
You probably want to use JLabel instead of JPanel. I know it sounds a bit unintuitive, but I'm not sure JPanel is suited to the purpose you are using it for. Also, JLabel can have a native ImageIcon set, so try using that.
public UserInterface() { // extends JLabel
this.setImageIcon(new ImageIcon("res/images/UIPanelImage.gif"));
// or super(~imageicon~)
}
Unlikely, but it could be that the image is not yet loaded when it gets drawn. You should use MediaTracker to manage that more carefully (although I'm not sure ImageIcon if takes care of this for you).
final static protected MediaTracker mediatracker = new MediaTracker(new Canvas());
static protected void checkImageIsReady(Image i) {
mediatracker.addImage(i, 1);
try {
mediatracker.waitForAll();
} catch (InterruptedException e) { }
mediatracker.removeImage(i);
}

How to display an image as a background on a JPanel

I have problem with displaying the image on JPanel when I rescaled the image according to the size of the JPanel. The image did not appear.
public class createGUII extends JFrame{
String [] background = {"c1.jpg","c2.jpg","c3.jpg","c4.jpg"};
ArrayList<String> bgPicturesFiles = new ArrayList<String>(Arrays.asList(background));
JPanel panel;
ImagePanel imgBg;
public createGUII(){
GridBagLayout m = new GridBagLayout();
Container c = getContentPane();
c.setLayout (m);
GridBagConstraints con = new GridBagConstraints();
//Panel for background
panel = new JPanel();
panel.setSize(600, 600);
con = new GridBagConstraints();
con.anchor=GridBagConstraints.CENTER;
con.gridy = 1; con.gridx = 0;
con.gridwidth = 1; con.gridheight = 1;
m.setConstraints(panel, con);
c.add(panel);
//randomized the image files
Random r = new Random();
int random = r.nextInt(bgPicturesFiles.size());
//rescale the image according to the size of the JPanel
imgBg = new ImagePanel(new ImageIcon(bgPicturesFiles.get(random)).getImage().getScaledInstance(panel.getHeight(), panel.getWidth(),Image.SCALE_SMOOTH));
panel.add(imgBg);
setResizable(false);
setVisible(true);
setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new createGUII();
}
});
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
Have a look at this: JPanel background image, JPanel with background image, with other panels overlayed
The second link mentions that you have to do some custom painting for scaling. This is a problem. I wouldn't scale the image every single time in the paintComponent method, but do it once if the width and height have been changed since the last call, and in that case, recreate a BufferedImage containing the image which you blit every single time before calling the superclass paintComponent, scaled up to the right size (use something like Image scaling does not work when original image height & width is smaller the scaling height & width). I can see an issue where it might try to fill the panel with a colour when you call the superclass paintComponent method, but you'll have to experiment.
The problem is that in Java images get loaded asynchronously. There are several issues with the above code because of that:
The image doesn't get loaded, so it's dimensions are (-1, -1). Thus, ImagePanel's size is invalid
Even if the dimensions get set manually (i.e. changing it to new Dimension(600, 600)), the image itself may not be loaded.
JFrame resizing is disabled. If you allow it, you would be able to get the image drawn with the above code by artificially making Swing load the image when the JFrame is resized
To ensure loading, add the following:
new ImageIcon(img).getImage();
after this.img = img; in ImagePanel's constructor.
Note that this is partially a hack - I'm not a GUI expert, but I get the idea the above could be written much better. Maybe somebody else might be able to shed more light.
Here are some links that might be helpful:
http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html
http://webcache.googleusercontent.com/search?q=cache:Ho0L4KoL44AJ:java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html+java+getscaledinstance&cd=1&hl=en&ct=clnk&gl=us&client=ubuntu (yes, it's from Google cache, the original link doesn't work...)
Hope this helps.
I don't see where you're actually reading the image, as suggested in this example.
Addendum: I've added an example of scaling. See also Don't Use getScaledInstance() and The Perils of Image.getScaledInstance().
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/** #see http://stackoverflow.com/questions/4170463 */
public class LoadImage extends JPanel {
private Image image;
public LoadImage() {
super(new GridLayout());
try {
image = ImageIO.read(new File("image.jpg"));
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
int w = image.getWidth(null) / 2;
int h = image.getHeight(null) / 2;
this.add(new JLabel(new ImageIcon(
image.getScaledInstance(w, h, Image.SCALE_SMOOTH))));
}
private void display() {
JFrame f = new JFrame("LoadImage");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new LoadImage().display();
}
});
}
}
Here is a link that should help. However I found a way that better suited the problem I had this was what I found, and the following is what I took from that.
I hope this helps.
Container con = getContentPane();
final String backgroundPath = "C:\\background.jpg";
ImageIcon imh = new ImageIcon(backgroundPath);
setSize(imh.getIconWidth(), imh.getIconHeight());
JPanel pnlBackground = new JPanel()
{
public void paintComponent(Graphics g)
{
Image img = new ImageIcon(backgroundPath).getImage();
g.drawImage(img, 0, 0, null);
}
};
con.add(pnlBackground);
pnlBackground.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());

Categories

Resources