我无法让我的 JMenuBar 出现在我的 paint() 方法旁边。
package Main;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Main extends JFrame{
int x, y; // axis position for oval
//JMenuBar Variables
JMenuBar menuBar;
JMenu file;
JMenuItem newGame;
JMenuItem checkScore;
JMenuItem exitGame;
// DOUBLE BUFFERING
private Image dbImage;
private Graphics dbGraphics;
Font font = new Font("Arial", Font.ITALIC, 30);
// KeyListener Class
public class KeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT){
if(x <=0){ // FRAME COLLISION DETECTION
x=0;
}else
x += -5; //decrement position to the left
}
if(keyCode == e.VK_RIGHT){
if(x >= 380){
x = 380;
}else
x += +5; //incrementing position to the right
}
if(keyCode == e.VK_UP){
if (y <= 25){
y = 25;
}else
y += -5; //decrementing position up
}
if(keyCode == e.VK_DOWN){
if(y >= 380){
y = 380;
}else
y += +5; //incrementing position down
}
}
}
// CONSTRUCTOR
public Main(){
// Window Properties
addKeyListener(new KeyListener()); // creates instance of KeyListener class
setTitle("Tower Defence");
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBackground(Color.CYAN);
// JMenuBar
menuBar = new JMenuBar();
file = new JMenu("File");
newGame = new JMenuItem("New Game");
checkScore = new JMenuItem("Check High Scores");
exitGame = new JMenuItem("Close Game");
menuBar.add(file);
file.add(newGame);
file.add(checkScore);
file.addSeparator();
file.add(exitGame);
setJMenuBar(menuBar);
// Display frame after all components added
setVisible(true);
// default position for oval
x = 150;
y = 150;
}
public void paint(Graphics g){
dbImage = createImage(getWidth(), getHeight()); // creates image of screen
dbGraphics = dbImage.getGraphics(); // gets graphics to be drawn in off screen image
paintComponent(dbGraphics); // paints graphics
g.drawImage(dbImage, 0, 0, this); // draw image to the visible screen
}
// PAINT GRAPHICS TO SCREEN
public void paintComponent(Graphics g){
g.setFont(font);
g.drawString("Hello World", 100, 200);
g.setColor(Color.red);
g.drawOval(x, y, 15, 15);
g.fillOval(x, y, 15, 15);
repaint();
}
// MAIN METHOD
public static void main(String[] args) {
new Main();
}
}
我看到了一个不同的问题,解决方案是覆盖paint方法并添加 super.paint(g); 当我尝试这个时,JMenuBar 出现但框架不断闪烁。