我正在制作一个具有2类(createJFrame
类和Handle
类)的汽车游戏,我使用JFrame,直到现在我都可以在没有JPanel的情况下绘制汽车,但是当创建JButton时,我创建了JPanel并向其中添加了JButton,然后没有更多的绘图,但是JButton仍然出现,这是我拥有的2类代码,creteJFrame
类仅创建一次,Handle
类将创建一次creteJFrame
类,然后在(Handle Class不使用JPanel进行绘制,而是使用
我从这段视频(https://www.youtube.com/watch?v=JrSjwQbTldg)中学到了"bg = getBufferStrategy();g = bg.getDrawGraphics(); g.drawRect()"
这种方法,下面是代码:
句柄类:
public Handle (){
gui = new creteJFrame(Width, Height, "GUI JFrame", this);
}
public static void main(String agrs[]){
new Handle();
}
public void draw(){ // This will loop
BufferStrategy bg = this.getBufferStrategy();
Graphics g = bg.getDrawGraphics();
g.drawImage(image, 10, 120, 80, 80);
g.dispose();
bg.show();
}
在creteJFrame类中:
public creteJFrame (int width, int height, String title, Handle handle)// Contrucstor
{
JFrame frame = new JFrame(title);
JPanel panel = new JPanel();
panel.setLayout(null); // If don't have this, i can't set Location of button
// Button
JButton buttonLeft = new JButton("Left");
buttonLeft.setBounds(400, 50, 90, 50);// set location of button
panel.add(buttonLeft);
frame.add(panel);
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(handle);
handle.start();
}