简体   繁体   中英

Can't get image to show up in swing

I'm a college student and this is my first time I have ever created a gui in Java. Right now I looked at this answer GUI in Java using Swing and followed the instructions and still nothing happens. Here is the code. I cut out all the irrelevant junk.

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Lab4Shell 
{
    // this holds the current game board
        private char[][] gameBoard = new char[7][8];
        private JButton[][] gameButtons = new JButton[7][8];

        private ImageIcon red = new ImageIcon("Red.jpg");
        private ImageIcon black = new ImageIcon("Black.jpg");
        private ImageIcon empty = new ImageIcon("Empty.jpg");

        private JPanel panel = new JPanel();

        private int currentPlayer = 1;
        private int numMoves = 0;
        //Why do you want everything in constructor?
        public Lab4Shell()
        {
            CreateWindow();
            ResetGame();



            // set layout
            // loop through buttons array creating buttons, registering event handlers and adding buttons to panel
            // add panel to frame
            // do other initialization of applet
        }

        public static void CreateWindow()
        {
            //Sets window title and create window object.
            JFrame aWindow = new JFrame("Connect Four");
            //Set window position and size
            aWindow.setBounds(500,100,400,400);
            //What close button does.
            aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Make window visible.
            aWindow.setVisible(true);


        }

        public static void main(String args[])
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {

                    Lab4Shell game = new Lab4Shell();

                }
            });


        }
void ResetGame()
        {



            JLabel label = new JLabel();
            label.setIcon(empty);
            for(int r=0;r<gameBoard.length;r++)
            {
                java.util.Arrays.fill(gameBoard[r],0,gameBoard[r].length,'0');



                //loop through board columns
                for(int c=0;c<gameBoard[r].length;c++)
                {

                }

            }
            // loop through array setting char array back to ' ' and buttons array back to empty pic
            // reset currentPlayer and numMoves variables
        }

You can try this

BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add( picLabel );

You have to add the created ImageIcons to the panel as Manos said, and being the images at the src folder of Eclipse project, do that:

java.net.URL url = getClass().getResource("red.JPEG");
ImageIcon red = new ImageIcon(url);

If the resources are embedded with the application (within in the jar), the you need to use Class#getResource to load them.

The preferred mechanism for loading images is through the ImageIO API . It supports more image formats (as well as providing a pluggable architecture) and guarantees an image that is ready to be displayed once the read method returns

BufferedImage redImage;

// ... 

URL url = getClass().getResource("red.JPEG");
if (url != null) {
    redImage = ImageIO.read(url);
} else {
    throw new NullPointerException("Unable to locate red image resource");
}

You've never adding anything to your frame - which is causing your problem. So in you createWindow method, you need to call:

aWindow.setContentPane(panel);

Then later on (like in your resetGame method), you'll add your content (like the JLabel ) to the panel:

panel.add(empty);

Where it's added to your panel is determined by the LayoutManager of the panel (there are many of them - the default is BorderLayout )

Other helpful things:

  • Generally, when it makes sense, create/initialize your objects in the constructor and add/remove/update them in the runtime.
  • For troubleshooting, use the .setOpaque(true) and .setBackground(Color.blue) methods on what you want to see. If you don't see it then, either something is covering it up, or it was never added

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM