gpt4 book ai didi

java - 奇怪的 Swing 故障?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:07:45 25 4
gpt4 key购买 nike

我不明白这一点,我目前正在为我正在制作的游戏制作主菜单,但出于某种原因,当我将鼠标悬停在 JButton 上时,它会在 JFrame 的左上角闪烁。我没有任何 mouseAction 方法或任何东西,它是我正在使用的 gif 吗?我不确定...

这是错误的截图

http://i.stack.imgur.com/BTUmP.png

这是我的代码:

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);
}
}
}

最佳答案

paintComponent() 方法中的第一条语句应该始终是:

super.paintComponent(g); 

确保背景被清除。

还有:

  1. 不要在绘画方法中执行 I/O。绘画方法只是为了绘画。在类的构造函数中读取图像,并在实例变量中读取图像。

  2. 类名应该以大写字符开头。想一想 JDK 中的所有类并遵循标准。

  3. 无需创建自定义类来绘制图像。只需使用带有图标的 JLabel。

关于java - 奇怪的 Swing 故障?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36754013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com