在JFrame中显示图像?

huangapple go评论59阅读模式
英文:

How to display an image in an JFrame?

问题

抱歉,我只会为您提供翻译的部分,不会回答关于翻译的问题。以下是您提供的代码的翻译:

我是一个初学者正在尝试编写一个小游戏不幸的是我目前无法将图像文件插入到JFrame中

我从互联网上获得了这个版本但不幸的是在我运行它时什么都没有显示

希望这有助于您解决问题。如果您需要更多帮助,请随时提出。

英文:

I am a beginner and am trying to program a small game. Unfortunately, I am currently failing to insert an image file on the JFrame.

I got this version from the internet, but unfortunately nothing is displayed when I run it.

import java.awt.*;
import javax.swing.*;

public class Draw extends JLabel {

	protected void paintComponent(Graphics g) {

		super.paintComponent(g);
		Graphics2D Graphic1 = (Graphics2D) g;

		Graphic1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

		g.setColor(new Color(0, 191, 255)); // farbe hintergrund einstellen
		g.fillRect(0, 0, Var.Framebreite, Var.Framehöhe);

		g.setColor(Color.yellow);

		Font currentFont = g.getFont(); // schriftgröße von Leben bestimmen
		Font newFont = currentFont.deriveFont(currentFont.getSize() * 8F);
		g.setFont(newFont);

		double b = Math.round(0.125 * Var.Framebreite);
		int h = (int) b;

		g.drawString("" + Var.LebenSpieler1, Var.Framebreite / 2 - h - 100, 90); // Leben anzeige spieler
																					// !muss "" + variable geschriebeen
																					// werden

		g.drawString("" + Var.LebenSpieler2, Var.Framebreite / 2 + h, 90); // Lebven anzeigen gegnerspieler

		ImageIcon icon = new ImageIcon("C:\\Users\\justi\\OneDrive\\Desktop\\OnlineSchule\\Englisch\\Test.PNG");
		JLabel l1 = new JLabel(icon);
		JPanel feld = new JPanel();
		feld.add(l1);
		feld.setBounds(30, 30, 110, 110);

		repaint();

	}
}

答案1

得分: 1

  1. 不要在绘图方法中创建组件。绘图方法用于使用 Graphics 对象进行绘图。
  2. 不要在绘图方法中调用 repaint()。这会导致循环。如果需要动画,请使用 Swing 定时器。
  3. 不要在绘图方法中进行 I/O 操作。该方法会频繁调用,您希望绘图效率高。

阅读 Swing 教程中有关自定义绘图的部分,以获取有关如何进行绘图的示例。下载可工作的代码并根据您的要求进行修改。

要绘制图像,您可以使用 Graphics 对象的 drawImage(...) 方法。您可以在构造函数中读取图像,并保留一个实例变量来引用该图像。

英文:
  1. Do not create components in a painting method. A painting method is used to do painting with a Graphics object.
  2. Do not invoke repaint() in a painting method. This will cause a loop. If you need animation use a Swing Timer.
  3. Do not do I/O in a painting method. The method will be called frequently and you want the painting to be efficient.

Read the section from the Swing tutorial on Custom Painting for examples of how to do painting. Download the working code and modify it for your requirments.

To paint an image you use the drawImage(...) method of the Graphics object.

You would read the image in your constructor and keep an instance variable to reference the image.

huangapple
  • 本文由 发表于 2020年8月2日 05:52:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63210404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定