我正在用java制作一个游戏,我想拥有能够运行游戏并关闭游戏的按钮。两个按钮都可以工作,但只有在我将鼠标悬停在它们上面后才显示。
public class Menu extends JPanel {
static boolean load = false;
JButton play = new JButton("play");
JButton close= new JButton("close");
boolean g = false;
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
draw(g2d);
add(play);
add(close);
}
public Menu(){
setLayout(new FlowLayout());
setVisible(true);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
g = true;
GamePanel.store1.clear();
if(g){
GamePanel panel = new GamePanel();
panel.setPreferredSize(new Dimension(560,680));
add(panel,0,0);
panel.setFocusable(true);
panel.requestFocusInWindow();
validate();
}
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public void draw(Graphics2D g2d){
g2d.drawImage(getBulletImage(),0,0,null);
}
// gets the image file for the player class
public Image getBulletImage(){
ImageIcon ic = new ImageIcon("Menu.png");
return ic.getImage();
}
谢谢!
答案 0 :(得分:1)
以下是我看到的问题。
在构造函数中读取一次图像,然后根据需要多次绘制。
不要覆盖JPanel绘制方法。覆盖JPanel paintComponent方法。
我根本看不到您的JFrame实例化,但请务必使用SwingUtilities invokeLater方法实例化您的JFrame。
我不确定这些提示会解决您的问题,因为您没有为我们任何人提供可运行的代码进行测试。
答案 1 :(得分:0)
将paint()中的add()方法调用移动到构造函数
中