最近我一直在尝试在 java 中复制 Space Invaders,以帮助学习使用 java 和一般编程语言开发应用程序。但是我在使用 JFrame 时遇到了一个小问题:我为窗口声明的背景颜色没有保留,它只是闪烁然后恢复为默认值。这是我的代码:
import javax.imageio.ImageIO;`
import java.io.*;`
import javax.swing.*;`
import java.awt.*;`
import java.awt.image.*;`
import java.awt.image.ImageObserver;`
import java.awt.event.*;`
public class Invaders extends JPanel{
public static int x = 40;
public static int y = 345;
public static int h = 20;
public static int k = 180;
public static int move = 1;
static final Invaders m = new Invaders();
public static void main(String[] args){
final JFrame frame = new JFrame("Movement of 2d Shapes");
frame.setSize(404,390);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(m);
frame.setBackground(Color.BLACK);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Action actionRight = new AbstractAction(){
public void actionPerformed(ActionEvent actionRightEvent){
if(x <= 350){
x += 10;
m.repaint();
};
}
};
Action actionLeft = new AbstractAction(){
public void actionPerformed(ActionEvent actionLeftEvent){
if(x >= 10){
x -= 10;
m.repaint();
};
}
};
KeyStroke right = KeyStroke.getKeyStroke("RIGHT");
KeyStroke left = KeyStroke.getKeyStroke("LEFT");
InputMap inputMap = m.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(right, "RIGHT");
inputMap.put(left, "LEFT");
m.getActionMap().put("RIGHT", actionRight);
m.getActionMap().put("LEFT", actionLeft);
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
draw(g);
cpu_move(m);
}
public void cpu_move(Invaders m){
if(h == 0){
move = 0;
}else if(h == 375){
move = 1;
}
if(move == 0){
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
h += 5;
m.repaint();
}else if(move == 1){
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
h -= 5;
m.repaint();
};
}
public void draw(Graphics g){
try{
g.drawImage(ImageIO.read(getClass().getResource(
"images/Ship.jpg")), x, y, 35, 23, Color.BLACK, null);
g.drawImage(ImageIO.read(getClass().getResource(
"images/Alien.jpg")), h, k, 28, 20, Color.BLACK, null);
}catch(IOException k){
Component temporaryLostComponent = null;
JOptionPane.showMessageDialog(temporaryLostComponent,
"one or more image files missing or corrupt");
}
}
}
背景颜色的声明有什么问题?编译时没有错误,但它仍然这样做。我究竟做错了什么?