我不明白这一点,我正在为我正在制作的游戏制作一个主菜单,但出于某种原因,当我将鼠标悬停在JButton上时,它会在JFrame的左上方闪烁.我没有任何mouseAction方法或任何东西,是我正在使用的gif吗?我不确定...
这是一个错误的屏幕抓图
这是我的代码:
import javax.swing.*;
import java.awt.*;
public class MainMenu {
JFrame frame = new JFrame("Frasergatchi");
public void display(){
frame.setSize(400,400);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
public void addComponents(){
JButton play = new JButton("Play");
JButton instructions = new JButton("Instructions");
JButton exit = new JButton("Exit");
JPanel panel = new JPanel();
paintMenu paintMenu = new paintMenu();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.add(panel);
play.setAlignmentX(Component.CENTER_ALIGNMENT);
instructions.setAlignmentX(Component.CENTER_ALIGNMENT);
exit.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(paintMenu);
panel.add(play);
panel.add(instructions);
panel.add(exit);
}
public class paintMenu extends JPanel{
public void paintComponent(Graphics graphics){
Image dog = new ImageIcon(getClass().getResource("DogMenuImage.gif")).getImage();
graphics.drawImage(dog,170,240,this);
}
}
}
Run Code Online (Sandbox Code Playgroud)
方法中的第一个语句paintComponent()
应始终为:
super.paintComponent(g);
Run Code Online (Sandbox Code Playgroud)
确保背景清除.
也:
不要在绘画方法中进行I/O. 绘画方法仅用于绘画.在类的构造函数中读取图像,并在实例变量中读取相同的图像.
类名应该以大写字符开头.考虑JDK中的所有类并遵循标准.
无需创建自定义类来绘制图像.只需使用带有Icon的JLabel即可.