gpt4 book ai didi

java - 显示图像 JFrame

转载 作者:行者123 更新时间:2023-12-02 04:40:55 26 4
gpt4 key购买 nike

我是 Java 新手,我正在尝试在 JFrame 上显示图像。我有主课:

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);
}

}

和球类:

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);
}
}

我想在主窗口中显示球图像。我该怎么做?

我看到了一些关于 repaint() 和 PaintComponent 的东西。我只想在框架上绘制球图像。提前致谢!

最佳答案

首先,您需要将自定义组件 PingPong 添加到 frame。然后将调用自定义paintComponent(Graphics g)

然后在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);
}

}

关于java - 显示图像 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com