我有一个JFrame,JPanel在其中。我的游戏背景完全是黑色的,因为实体位于其顶部。我只是想以“最简单”的方式将背景从计算机上更改为图像,而无需进行太多更改。
public Game() {
// Frame
JFrame container = new JFrame("Space Invaders");
// Resolution
JPanel panel = (JPanel) container.getContentPane();
panel.setPreferredSize(new Dimension(800,600));
panel.setLayout(null);
// Canvas Size
panel.setBounds(0,0,800,600);
panel.add(this);
// Window Visible
container.pack();
container.setResizable(false);
container.setVisible(true);
container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
使用aJLabel
作为背景组件...
JFrame container = new JFrame("Space Invaders");
JLabel label = new JLabel(new ImageIcon(ImageIO.read(...)));
label.setLayout(new BorderLayout());
container.setContentPane(label);
// Resolution
// There are simply so many different ways to achieve this
// that are better it's not funny
//JPanel panel = (JPanel) container.getContentPane();
//panel.setPreferredSize(new Dimension(800, 600));
//panel.setLayout(null);
// Canvas Size
//setBounds(0, 0, 800, 600);
//panel.add(this);
// Window Visible
container.pack();
container.setResizable(false);
container.setVisible(true);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Pointless
//container.addWindowListener(new WindowAdapter() {
// public void windowClosing(WindowEvent e) {
// System.exit(0);
// }
//});
问题是:
icon
andtext
属性计算preferredSize
标签的java.awt.Canvas
,则它将在此组件上绘制,因为java.awt.Canvas
它不能透明。用于Graphics#drawImage
在渲染器重置内容之前绘制背景图像。
通常,这将是一个更好的解决方案,因为您可以完全控制图像的大小和位置,并且如果您使用的java.awt.Canvas
是BufferStrategy
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句