我从未真正创建过JPanel
,但我似乎在JFrame
内部遇到了问题。我的“fball”对象随机出现在屏幕上,我无法弄清楚为什么对我的生活。我实际上并没有创建JPanel
并使用方法来设置它,并且不知道如何做到这一点,因为我的扩展JPanel
的类只创建了一个图像。如果你帮助我,我会永远爱你。 (我为我在java中缺乏知识而道歉)
以下是我的Window类的代码:
package game.thirdTry;
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Window extends JFrame {
private static Window instance;
public static Window getInstance() {
if(instance == null) {
instance = new Window("Game");
}
return instance;
}
private Window(String name) {
super(name);
setSize(1200, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(null);
addKeyListener(new UserInput());
WindowStructure banner = new WindowStructure("Beatles Logo.jpg", 0, 0, getWidth(), 75);
//WindowStructure fball = new WindowStructure("fireball.100x100.png", 100, 100, 100, 100);
WindowStructure fball = WindowStructure.getInstanceF();
System.out.println("Fball.xSize: " + fball.xSize + ", Fball.ySize: " + fball.ySize);
System.out.println("Fball.xLoc: " + fball.xLoc + ", Fball.yLoc: " + fball.yLoc);
banner.setBounds(banner.xLoc, banner.yLoc, banner.xSize, banner.ySize);
fball.setBounds(fball.xLoc, fball.yLoc, fball.xLoc + fball.xSize, fball.ySize + fball.ySize);
add(fball, null);
add(banner, null);
setVisible(true);
while(true){
System.out.println("Fball.xLoc: " + fball.xLoc + ", Fball.yLoc: " + fball.yLoc);
repaint();
try{
Thread.sleep(100);
}catch (Exception e){
}
}
}
/*
public void paint(Graphics g) {
super.paintComponents(g);
}
*/
}
Image Creation Classs (extends JPanel):
package game.thirdTry;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class WindowStructure extends JPanel {
private static WindowStructure fball;
public static WindowStructure getInstanceF(){
if(fball == null){
fball = new WindowStructure("fireball.100x100.png", 300, 100, 100, 100);
}
return fball;
}
ImageIcon imageIcon;
int xLoc, yLoc, xSize, ySize;
public WindowStructure(String bannerImg, int xLoc, int yLoc, int xSize, int ySize){
URL bannerImgURL = getClass().getResource(bannerImg);
imageIcon = new ImageIcon(bannerImgURL);
this.xLoc = xLoc;
this.yLoc = yLoc;
this.xSize = xSize;
this.ySize = ySize;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(imageIcon.getImage(), xLoc, yLoc, xSize, ySize, null);
}
}
答案 0 :(得分:0)
我无法看到你移动球的位置,但基本问题可能是你使用了框架的大小而不是框架的内容窗格。框架的大小包括框架顶部的栏(带最小化按钮,标题等)。
答案 1 :(得分:0)
我的" fball"对象在随机部分离开屏幕,我无法弄清楚为什么我的生活
fball.setBounds(fball.xLoc, fball.yLoc, fball.xLoc + fball.xSize, fball.ySize + fball.ySize);
你为什么设置" fball"宽度为(位置+尺寸)和高度为(尺寸+尺寸)?你不能为#34; banner"
做这件事