Putting an image in a JFrame

I'm trying to paint an image onto a JFrame. Im making a monopoly game and need to paint the board, and repaint it after every turn. I dont know how to put an image onto a JFrame and was wondering if anyone could give me a basic algorithm or code example of how to do this. Thanks.

Here is the basic algorithm to paint to a JFrame:
Don't do it!
Set the preferred size of a JPanel and add the JPanel to the JFrame. Paint to the JPanel by extending the paintComponent method. When you're ready to display, then remember to pack the JFrame and setVisible appropriately.
You can read about doing this in the Java Tutorial.
public void paintComponent(Graphics g){ //override in JPanel
  super.paintComponent(g);
  //do what ever you need to do here to draw your graphics.
}I prefer to do all of my drawing to a BufferedImage and then use drawImage to show the image (off screen rendering):
public void paintComponent(Graphics g){ //override in JPanel
  g.drawImage(myImage, 0, 0, this);
}

Similar Messages

  • Putting an image into a JFrame or a JPanel

    Hello everybody,
    I'd like to know how to put an image (a real one, not a small icon we can't see it!) into a JFrame, or a JPanel, or included into a miscellanea element (label, textfield or somethiong else).
    Thanks,
    Regards
    Cedric

    Hi Cedric,
    If the image format is Jpg or gif, then the best way to insert the image
    into the Frame or panel is to use JLabel. You can pass the argument to the file as parameter to JLabel construction.
    For other formats, you have the option of using drawimage in paint function of applets.
    Hope this helps.
    Best Regards,
    Chandru

  • Putting an Image in JPanel

    I am trying to put an image in JPanel. Using something other than ImageIcon. When I run the program only a white screen appears.
    package game;
    import gui.FullScreenDisplay;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.Runnable;
    import java.lang.Thread;
    public class Runner implements Runnable
         private static final long serialVersionUID = 1L;
         private FullScreenDisplay display;
         public static void main(String args[])
              Thread t = new Thread(new Runner());
              t.start();
         public Runner()
              makeGui();
         private void makeGui()
              display = new FullScreenDisplay(this);
         public void run()
              try {
                   Thread.sleep(1000);
              } catch (InterruptedException e) {/*Nothing to do*/}
              run();
         public void quit()
              System.exit(0);
    package gui;
    import game.Runner;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.KeyEvent;
    import javax.swing.KeyStroke;
    import javax.swing.AbstractAction;
    import java.awt.event.ActionEvent;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.imageio.ImageIO;
    import java.io.File;
    import java.io.IOException;
    public class FullScreenDisplay extends JFrame {
         private static final long serialVersionUID = 1L;
         private Runner master;
         private JPanel mainPanel;
         private Image tempImage;
         public FullScreenDisplay(Runner master)
              super();
              //Remove this eventually.
              try {
                   tempImage = ImageIO.read(new File("test_image.jpg"));
              } catch (IOException e) {
                   System.out.println("image get error");
                   e.printStackTrace();
              this.master = master;
              makeFrame();
              makePanel();
              makeKeyBindings();
              //setFullScreen(chooseBufferStrategy());
              setFullScreen();
              requestFocus();
              setVisible(true);
              //Remove this eventually.
              Graphics g = tempImage.getGraphics();
              mainPanel.paint(g);
              this.update(g);
         private void makeFrame()
              setUndecorated(true);
              setResizable(false);
              setFocusable(true);
         private void makePanel()
              mainPanel = new JPanel(){
                   public void paintComponent(Graphics g) {
                        if(tempImage == null){
                             System.out.println("Balls");
                        g.drawRect(10, 10, 10, 10);
                        g.drawImage(tempImage,0,0,null);
                        super.paintComponent(g);
                        System.out.println("Did it work");
              add(mainPanel);
         private void makeKeyBindings()
              mainPanel.setFocusable(true);
              //Key bindings... don't like using a string to index, find out if there's a better way.
              mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "exit");
              mainPanel.getActionMap().put("exit", new AbstractAction(){
                   public void actionPerformed(ActionEvent e)
                        master.quit();
         /*private void chooseBufferSrategy()
         private void setFullScreen()
              GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
    }

    super.paintComponent(g);should be the first line in paintComponent()
    also, you don't really need the keyBindings to quit,
    just set the default close to exit and Alt-F4 will close/quit

  • Putting an Image in my CoordinateArea

    Hey,
    I would like to be able to place an image within my CoordinateArea, and I also want this image to be able to respond to being clicked on when the mouse is clicked between certain co-ordinates. Here is my code so far...
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import javax.swing.event.MouseInputListener;
    public class tourWelby extends JFrame {
    JLabel label = new JLabel();
    JPanel panel = new JPanel();
    Point clickPoint = new Point();
    Point cursorPoint = new Point();
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
              JFrame frame = new JFrame("TourWelby");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              tourWelby controller = new tourWelby();
              controller.buildUI(frame.getContentPane());
              //Create and set up the content pane.
              frame.getContentPane().setBackground(Color.BLACK);
              // Create the menu bar
              JMenuBar menu = new JMenuBar();
              menu.setBackground(Color.BLACK);
              //Build the menus.
              JMenu file = new JMenu("File");
              file.setBackground(Color.BLACK);
              file.setForeground(Color.WHITE);
              JMenu test = new JMenu("Test");
              test.setBackground(Color.BLACK);
              test.setForeground(Color.WHITE);
              // Install the menu bar in the frame
              frame.setJMenuBar(menu);
              menu.add(file);
              menu.add(test);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setResizable(false);
              frame.setSize(800,700);
         private void buildUI(Container container) {
    container.setLayout(new BoxLayout(container,
    BoxLayout.PAGE_AXIS));
    CoordinateArea theArea = new CoordinateArea(this);
    container.add(theArea);
    label = new JLabel();
              label.setBackground(Color.BLACK);
              label.setForeground(Color.WHITE);
    resetLabel();
    container.add(label);
    public void updateCursorLocation(int x, int y) {
    if (x < 0 || y < 0) {
    cursorPoint = null;
    updateLabel();
    return;
    if (cursorPoint == null) {
    cursorPoint = new Point();
    cursorPoint.x = x;
    cursorPoint.y = y;
    updateLabel();
    public void updateClickPoint(Point p) {
    clickPoint = p;
    updateLabel();
    public void resetLabel() {
    cursorPoint = null;
    updateLabel();
    protected void updateLabel() {
    String text = "The cursor is at ";
                   if (cursorPoint != null) {
    text += "("
    + cursorPoint.x + ", " + cursorPoint.y + ") ";
    label.setText(text);
         public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    public static class CoordinateArea extends JComponent implements MouseInputListener {
    Point point = null;
    tourWelby controller;
    Dimension preferredSize = new Dimension(800,700);
    public CoordinateArea(tourWelby controller) {
    this.controller = controller;
                   setBorder(BorderFactory.createMatteBorder(3,3,3,3, Color.RED));
    addMouseListener(this);
    addMouseMotionListener(this);
    public Dimension getPreferredSize() {
    return preferredSize;
    //Methods required by the MouseInputListener interface.
    public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    if (point == null) {
    point = new Point(x, y);
    } else {
    point.x = x;
    point.y = y;
    controller.updateClickPoint(point);
    repaint();
    public void mouseMoved(MouseEvent e) {
    controller.updateCursorLocation(e.getX(), e.getY());
    public void mouseExited(MouseEvent e) {
    controller.resetLabel();
    public void mouseReleased(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) { }
    How do I go about putting an image in the CoordinateArea and making it clickable? Do I need to use an ImageIcon?
    Thanks in advance.

    Hi again everyone. I've gone and rethought my code and started again from scratch. Here is what I have come up with..
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.*;
    public class tourWelby extends JFrame  implements MouseListener {
    public void mouseReleased(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) { }
    public void mouseExited(MouseEvent e) { }
    public void mouseClicked(MouseEvent e) { }
    public static void main (String args[]) {
         new tourWelby();
         public tourWelby() {
         super("Test");
        Container content = getContentPane();
         Point clickPoint = new Point();
         Point cursorPoint = new Point();
         JLabel label = new JLabel();
         label.setText("Test");
         label.setBackground(Color.WHITE);
         label.setForeground(Color.WHITE);
         JPanel theArea = new JPanel();
         theArea.setPreferredSize(new Dimension(800, 600));
         theArea.setBackground(Color.BLACK);
         theArea.add(label);
         theArea.addMouseListener(this);
         addMouseListener(this);
         content.add(theArea);
             pack();
             setVisible(true);
         setResizable(false);
    }Basiclly now, I think I need to add the mouseListener to the JPanel. However I'm not sure where I need to put the "public void updateCursorLocation" code and such that I had before (before, I used some samples of code from another program, and I wasn't entirely sure how it worked). If someone could help me (again!) with getting the MouseListener to change the label on the JPanel, to reflect where the cursor is (as in my previous code) I would again, be most appreciative. Thanks.

  • Problem Displaying Images in a JFrame

    I am writing a program that displays images on a JFrame window. I have been reading the other postings about this topic however I have not been able to make my code work. I am hoping there is some obvious solution that I am not noticing. Please help, I am very confused!
    public class WelcomeWindow {
    private JLabel label;
    private ImageIcon logo;
    public WelcomeWindow() {
    label = new JLabel();
    logo = new ImageIcon("/images/logo.gif");
    label.setIcon(logo);
    this.getContentPane().add(label);

    Instead of a JLabel, have you tried to use a JButton containing the Icon?
    Also (but I think you've done it already), you could do that :
    File iconFile = new File("/images/logo.gif");
    if (!iconFile.isFile()) {
    System.out.println("Not a file");
    That way you'll be certain that the path given is correct.
    Hope this helps.

  • I can't figure out the Keynote title option. I'm a newbie so forgive my ignorance. I want to put an image in the swing arm, but I can't figure it out.

    I even tried opening in Motion and inserting it there, but when I bring it back to fc it's not there. I also want to change the background to an image or at least solid white. When I put an image in the Dropzone it doesn't show up. Any help would be GREATLY appreciated!

    To change the title background to use a clip in the drop zone, do just as Jim said.
    Also, place the clip that want to appear in the "swing arm" right below the title in the timeline.

  • I had all photos on a Windows desktop.  Got a mac laptop, installed LR5, and put all images from Windows onto an external hard drive.  When I go to import them into LR on the Mac, they are all locked.  Help, please.  Thanks

    I had all photos on a Windows desktop.  Got a mac laptop, installed LR5, and put all images from Windows onto an external hard drive.  When I go to import them into LR on the mac, they are all locked.  Help, please!

    "I plugged the external into the Mac and moved a folder of images onto the desktop.  It looks like it went from read only to not locked.  Is this possible?"
    Yes, that's exactly what happened. If you buy another drive, you could copy from your existing drive to the new and your files will be read/write. The new drive will have to be formatted as an HFS drive (that's the Mac's format). If you need to format it, you use Disk Utility which is in the Utilities folder on your Mac. Be careful with that -- it wipes out whatever is currently on the drive. Make sure you format the right drive.
    I keep all my images on an external drive, too. In fact, I have two matching drives and sync them so I always have a backup.

  • How to put an image in a data grid in Flex Builder 2

    Hi All,
    I need to populate a data grid with some text data received
    from a web service and, in a particular column of the datagrid, I
    have to put an image depending of a specific data returned me by
    the web service.
    It seems that there is the possibility to add an image in
    data grid column with the cellRenderer properties, but this
    property is available only for ActionScript 3.
    I'm developing an application in Flex Builder 2 that run
    ActionScript 2 and cellRenderer properties is not available. Is it
    right?
    If no, I will can use this cellRenderer properties in my
    application. Please, can you show me an example?
    If yes, there is a way to insert an image in datagridcolumn
    with ActionScript 2?
    Thank you very much
    Regards

    Flex Builder 2 uses Actionscript 3.
    You will need to write a renderer for for this column.
    There are a lot of examples of datagrids with images in them.
    here is one from the livedocs
    http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Live Docs_Book_Parts&file=cellrenderer_072_28.html

  • How to put an image in the popup help of a page item?

    I am using APEX 2.2. I want to put an image in the help text of a page input item.
    This is the help text:
    Some help text....
    <p><img src="&APP_IMAGES.auto_lov.jpg" /></p>This is rendered as:
    <p><img src="wwv_flow_file_mgr.get_file?p_security_group_id=0&p_flow_id=103&p_fname=auto_lov.jpg" /></p>As you can see, the application id is not returned.
    If I put exactly the same text in a html region, the image is correctly displayed:
    <p><img src="wwv_flow_file_mgr.get_file?p_security_group_id=844129086577364&p_flow_id=103&p_fname=auto_lov.jpg" />So, is it possible at all to put in image in the popup help text of a page item?

    I solved it by putting the jpg file in an images directory on the web server instead of in the database. Not really what I want, but it works.
    <p><img src="&IMAGE_PREFIX./apps/auto_lov.jpg" /></p>

  • How do I put an image in the background of a JDesktop?

    I have made a program that has a JDesktop. Just need to know the coding to put an image in the background of the JDesktop. Any suggestion?

    Add a JLabel that holds a picture to it. Make sure it's in the back layer.

  • How do I put an image in a spry tabbed panels tab

    Hello All,
    I am currently working on a site with Spry Tabbed Panels.
    One thing I'm not sure how to do is to put an image in each of the selecting tabs. I've done it before and I've forgot. I also have a site with an example of what I would like to do.
    http://emilymagnuson.com
    The tabs on this site were created with images inside of them. And I would like to know how to do it. I would like to make it work so the image changes when you click, hover, and deselect.
    Thank you.

    To put an image in the foreground, add it to your HTML code:
    <li class="TabbedPanelsTab" tabindex="0">
    <div style="margin-top:9px;"><img src="your_image_here.jpg">Contact</div>
    </li>
    Nancy O.

  • Inserting image in a jframe

    is it possible to insert an image into a jframe?
    as far as i noe, i can insert a jlabel, and etc. but how about an image?
    if it is possible, can someone please teach me how to do it and post me the codes.
    Thank you.

    You could use g.drawImage, but the simplest solution would be to add the image to a JLabel and add the JLabel to the JFrame.
    JLabel myLabel = new JLabel(new ImageIcon("yourimage.gif"));
    getContentPane().add(myLabel);

  • I don't know how to put an image instead of colours for background

    I am usin awt and I want to put an image from my HD as background instead typical colours. How can I do this?

    Ah. This one is mine. You can try making a Frame anonymus class and overriding paint(). Do you know how to get your picture?
    {=^)                                                                                                                                                                                                                                                                           

  • How can I put an image in the page header so that it will be repeated on every page?

    Hi to everyone!
    I want to create a Pages template with the logo of our company in the page header.
    I'd like to put that image (logo) in the page header so that it will be repeated on every page but it will not modify the content of the page.
    Anyone know how to achive this, or something similar without have to copy-paste that image every time we add a page to the document?
    Thanks in advance

    Takashi,
    Turn off the Page Headers (not absolutely necessary, but since you don't need it, why not)
    Put your Graphic on the page and make the following settings:
    Then Insert > Text Box and make the same settings as for the graphic.
    Place your "Header text" in the text box and arrange the box and graphic as you want them. Move both to Section Master using the Arrange menu.
    Jerry

  • Can't put photos/images in email (new email) in Mail

    Okay, this is weird. I can no longer drop a .jpg image (or any other) into a new email message. (This is with my prefs set to compose in Rich Text Format, yes. And this is 10.5.2.)
    If I try to drag it from the Photo Browser into a message, sometimes it appears as if it's going into the email message, but it does not appear in the body area. Sometimes it bounces back to the Photo Browser, as if the email message is an object that cannot receive a dropped image file. And if I try to drag an image file from Finder into the body of the message, I can get either behavior again.
    Either way, I can't put an image/photo/graphic file into an email message.
    Has anyone else seen this behavior and figured out a fix for it?

    An addendum...
    Just to make it really weird, I can drag image files from the Photo Browser to the Mail icon in the Dock and make a new email, and then I can see the image in the mail message. And once I have that e-mail message created by dragging an image the Dock icon, I can drag other images/files from the Photo Browser into the same new message and see them.

Maybe you are looking for