3

i am new to Java . i was just trying to load image as background in JFrame. What i wanted to do is get the image from C Drive(that is not my workspace) so what i did in Board.java:

   ImageIcon i = new ImageIcon("C:/image.png");
   img =i.getImage();

and did try to paint it something like this:

    public void paint(Graphics g )
    { 
    super.paint(g);
    Graphics2D  g2d= (Graphics2D) g;
    g2d.drawImage(img, 0, 100, null);
    }

And then i am calling in my main class like this

   public static void main(String[] args) 
   {
    JFrame frame= new JFrame(" Game") ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1200, 365);
    frame.setVisible(true);
    frame.add(new Board());

   }

but i am not getting any image displayed , so is it legal way to add Image ?

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • when you debug what is inside ImageIcon? – Woot4Moo Nov 05 '12 at 18:16
  • i have mentioned path to image.png, directly from c drive , that is what i am trying to do if possible . –  Nov 05 '12 at 18:17
  • If this is windows, shouldn't it be `ImageIcon i = new ImageIcon("C:\1.png");`? (backslash instead of forwardslash) – sampson-chen Nov 05 '12 at 18:18
  • @sampson-chen : in any case, it should be `"C:\\1.png"` . But that's not the problem, "C:/image.png" should work the same – leonbloy Nov 05 '12 at 18:19
  • i have tried both , none of them working , i did code it as per a tutorial instructions and there is no error but problem with loading image , when compile no image –  Nov 05 '12 at 18:22
  • Did you debug? If so , then what is inside `imageIcon` – Mukul Goel Nov 05 '12 at 18:25

4 Answers4

4
  • Do not override paint() in JFrame
  • Do not call setSize() on JFrame rather use JFrame#pack() before setting it visible
  • Get into the habit of using / as regardless of platform this is supported.

Here is an example I made:

enter image description here

  • Create JPanel/JLabel instance
  • Override paintComponent(..) in JPanel/JLabel
  • Override getPreferredSize() to return dimensions/component which is correctly sized to Image
  • Add JPanel/Jlabel to JFrame instance
  • pack JFrame by JFrame#pack()
  • set JFrame visible

Test.java:

//necessary imports
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    static String filename = "c:/test.jpg";//your file path and name here use / as it will work on linux platforms too so get into the habbit

    /**
     * Default constructor
     */
    public Test() throws Exception {
        initComponents();
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() throws Exception {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Image background = ImageIO.read(new File(filename));
        final Dimension jpanelDimensions = new Dimension(new ImageIcon(background).getIconWidth(), new ImageIcon(background).getIconHeight());

        frame.add(new JPanel() {
            @Override
            protected void paintComponent(Graphics grphcs) {
                super.paintComponent(grphcs);
                grphcs.drawImage(background, 0, 0, null);
            }

            //return a JPanel that matches images size
            @Override
            public Dimension getPreferredSize() {
                return jpanelDimensions;
            }
        });

        frame.setResizable(false);

        //pack frame (size JFrame to match preferred sizes of added components and set visible
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    //set nimbus look and feel
                    for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
                    e.printStackTrace();
                }
                try {
                    //create GUI instance
                    Test test = new Test();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
0

use this format location instead

C:\\1.png
Sudheera
  • 1,727
  • 1
  • 12
  • 28
0

With Swing you have to use paintComponent() in place of paint().

Aubin
  • 14,617
  • 9
  • 61
  • 84
  • but there is not any image , can you please check the above mentioned code and let me know the problem . –  Nov 05 '12 at 18:25
  • `JFrame` has no `paintComponent(Graphics)` method, which the OP can (and should) confirm using `@Override` notation. This is one of the reasons why most people experienced with Swing will advise **not** to paint directly to a top-level container, but instead add a custom panel to it & take it from there. – Andrew Thompson Nov 05 '12 at 23:42
  • Board.java doesn't inherit from JFrame. See frame.add( board ) – Aubin Nov 06 '12 at 08:22
0

In your code:

Move frame.add(new Board()); to before frame.setVisible(true);, i.e.:

Also, add frame.pack();

public static void main(String[] args) 
{
    JFrame frame= new JFrame("Game") ;
    frame.add(new Board());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1200, 365);
    frame.pack();
    frame.setVisible(true);
}

Once the JFrame is set to visible, only the event dispatch thread is supposed to touch it.

As a side note, override paintComponent() instead of paint() unless you know exactly what you are doing: http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html

The gist is that paint() is actually responsible for invoking the following: paintComponent(), paintBorder(), and paintChildren(). So if you just override paint() blindly, it will change the behavior of your component in ways you may not want.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81
  • 1
    Calling `setSize()` and `pack()` on the same `JFrame` instance really shouldn't be done. Also all Swing components should be created and changed in `Event Dispatch Thread` via `SwingUtilities.invokeXXX` – David Kroukamp Nov 05 '12 at 19:21