Having images as background of JPanel(将图像作为 JPanel 的背景)
问题描述
我是 Java 新手,目前正在创建一个带有图形的游戏.我有这个类从 JFrame
扩展而来.在这个类中,我有许多需要图像作为背景的 JPanel
.据我所知,为了能够在 JPanel 中绘制图像,我需要有一个从 JPanel 扩展而来的单独类,并且该类的 paintComponent
方法将完成这项工作.但是我不想为每个 JPanel
单独的类,我有太多的类;而且我只关心背景.我怎样才能做到这一点?是匿名内部类吗?怎么样?
I am new in Java and I am currently creating a game with graphics. I have this class that extends from JFrame
. In this class, I have many JPanel
s that needs an image as background. As I know, to be able to paint images in the JPanel, I need to have a separate class that extends from JPanel and that class's paintComponent
method will do the work. But I don't want to make separate classes for each JPanel
, I have too many of them; and with the fact that I am only concerned with the background. How can I do this? is it with an anonymous inner class? How?
为了更好地理解,我提供了一些代码:
For better understanding I provided some code:
public GUI extends JFrame {
private JPanel x;
...
public GUI() {
x = new JPanel();
// put an image background to x
}
推荐答案
为什么不创建一个接受 Image
的单个类??
Why not make a single class that takes a Image
??
public class ImagePane extends JPanel {
private Image image;
public ImagePane(Image image) {
this.image = image;
}
@Override
public Dimension getPreferredSize() {
return image == null ? new Dimension(0, 0) : new Dimension(image.getWidth(this), image.getHeight(this));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(image, 0, 0, this);
g2d.dispose();
}
}
你甚至会提供关于应该在哪里绘制的提示.
You would even provide hints about where it should be painted.
这样,您可以在需要时简单地创建一个实例
This way, you could simply create an instance when ever you needed it
更新
另一个问题是,为什么?
The other question is, why?
您可以只使用 JLabel
来为您绘制图标,而无需任何额外工作...
You could just use a JLabel
which will paint the icon for you without any additional work...
有关详细信息,请参阅 如何使用标签..
See How to use labels for more details...
这实际上是一个坏主意,因为 JLabel
在计算其首选尺寸时不使用它的子组件,它仅在确定其首选尺寸时使用图像的大小和文本属性,这个可能导致组件尺寸不正确
This is actually a bad idea, as JLabel
does NOT use it's child components when calculating it's preferred size, it only uses the size of the image and the text properties when determining it's preferred size, this can result in the component been sized incorrectly
这篇关于将图像作为 JPanel 的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将图像作为 JPanel 的背景
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01