有一个问题我不明白:为什么我能够用 drawImage()
绘制图像方法如果 JFrame
的布局是 BorderLayout
或GridLayout
但不是GridbagLayout
, FlowLayout
或BoxLayout
?有人可以给我解释一下吗?
这是代码:
package footballQuestioner;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class attempter {
public static void main(String[] args) {
JFrame frame = new Beispielfenster();
}
}
class Beispielfenster extends JFrame {
private class TransparentBG extends JLabel {
BufferedImage image;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
try {
image = ImageIO
.read(TransparentBG.class
.getClassLoader()
.getResourceAsStream(
"footballQuestioner/rightAnswerSign.png"));
} catch (IOException e) {
e.printStackTrace();
}
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
}
}
public Beispielfenster() {
//setLayout(new FlowLayout());
JPanel panel=new JPanel(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label=new TransparentBG();
panel.add(label);
add(panel);
pack();
centeringWindow();
setVisible(true);
}
public void centeringWindow() {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x;
int y;
x = (int) (dimension.getWidth() - getWidth()) / 2;
y = (int) (dimension.getHeight() - getHeight()) / 2;
setLocation(x, y);
}
}
最佳答案
因为使用前两个布局,JLabel 将填充容器,此处为 JPanel。对于其他布局,它将调整其首选大小,即 0。如果您希望使用其他布局,请考虑覆盖 getPreferredSize。
另请注意:
- 您不应在没有 PaintComponent 方法的情况下读取图像文件。
- 如果可能的话,您不应该重新读取图像文件(如果您在重复调用的方法中读取图像,就会发生这种情况)。读取它们一次(例如在构造函数中),并将它们存储在字段中。
- 您不应处置 JVM 为您提供的 Graphics 对象,而只能处置您自己创建的 Graphics 对象(例如来自 BufferedImage 的对象)。
编辑
例如,像这样:
private class TransparentBG extends JLabel {
BufferedImage image;
public TransparentBG() throws IOException {
image = ImageIO.read(TransparentBG.class.getClassLoader()
.getResourceAsStream("footballQuestioner/rightAnswerSign.png"));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (image != null) {
g2d.drawImage(image, 0, 0, null);
}
// g2d.dispose();
}
@Override
public Dimension getPreferredSize() {
if (image != null) {
int w = image.getWidth();
int h = image.getHeight();
return new Dimension(w, h);
}
return super.getPreferredSize();
}
}
关于java - 当我为 JFrame 使用 FlowLayout 时,为什么我的图像没有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728581/