Java jbuttons仅在我将鼠标悬停在其上方后显示

Java jbuttons仅在我将鼠标悬停在其上方后显示,java,swing,jpanel,jbutton,Java,Swing,Jpanel,Jbutton,我正在用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(Graphi

我正在用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();
}

谢谢

将add()方法调用从paint()移动到构造函数中

以下是我看到的问题

  • 在构造器中读取图像一次,然后根据需要多次绘制

  • 不要重写JPanel绘制方法。重写JPanel paintComponent方法

  • 我根本看不到您的JFrame实例化,但请确保使用SwingUtilities invokeLater方法实例化JFrame


  • 我不确定这些技巧能否解决您的问题,因为您没有提供可运行的代码供我们任何人测试。

    为什么要从paint()调用add()?这似乎是一个可怕的想法。为了更快地获得更好的帮助,请发布一个(最小的完整和可验证的示例)。我这样做了,但没有任何改变。还有其他想法吗?尝试重写paintComponent()或paintComponents()而不是paint()。并将add()方法保留在构造函数中。