简体   繁体   中英

Display Image JFrame

I'm new to Java and I'm trying to display an image on JFrame. I have the main class:

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class PingPong extends JPanel{

    Ball ball = new Ball(this); 

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
    }

    public static void main(String[] args){
        /* Creating the frame */
        JFrame frame = new JFrame();
        frame.setTitle("Ping Pong!");
        frame.setSize(600, 600);
        frame.setBounds(0, 0, 600, 600);
        frame.getContentPane().setBackground(Color.darkGray);
        frame.add(new JLabel(new ImageIcon("images/Table.png")));
        frame.setVisible(true); 
    }

}

and Ball class:

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;


public class Ball {
    int x,y;
    ImageIcon ball = new ImageIcon("images/Ball.png");
    Image ballImage = ball.getImage();

    public Ball(JPanel panel){
        this.x = panel.getWidth()/2;
        this.y = panel.getHeight()/2;
    }
    public void repaint(Graphics g){
        g.drawImage(ballImage, x, y, null);
    }
}

I want to display the Ball image in the main. How can I do it?

I saw something with repaint() and paintComponent. I just want to draw the ball image on the frame. Thanks in advance!

You have to use the ball class in your main method. There isn't an instantiated ball object inside any method, only an instance of the Ball class inside the Pong class.

You also never paint the method in the frame created in the main method.

Fist you need to add your custom component PingPong to frame . Then custom paintComponent(Graphics g) will be called.

Secondly add drawing code to paintComponent(Graphics g) .

public class PingPong extends JPanel {

  private static final long serialVersionUID = 7048642004725023153L;

  Ball ball = new Ball();

  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    ball.paint(g);
  }

  public static void main(String[] args) {
    /* Creating the frame */
    JFrame frame = new JFrame();
    frame.setTitle("Ping Pong!");
    frame.setSize(600, 600);
    frame.setBounds(0, 0, 600, 600);
    frame.getContentPane().setBackground(Color.darkGray);
    frame.add(new PingPong());
    frame.setVisible(true);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  }

}

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