简体   繁体   English

我将鼠标悬停在它们上方后才显示

[英]jbuttons only showing after i hover over them

i am making a game in java and i want to have buttons that will run the game and close the game. 我正在用Java开发游戏,并且我想拥有一些可以运行游戏并关闭游戏的按钮。 both buttons work but they only show up after i hover over them. 这两个按钮都可以使用,但是只有当我将鼠标悬停在它们上方时,它们才会显示出来。

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

thanks! 谢谢!

Here are the problems I see. 这是我看到的问题。

  1. Read your image once in the constructor, then draw it as many times as you wish. 在构造函数中读取一次图像,然后根据需要绘制多次。

  2. Don't override the JPanel paint method. 不要重写JPanel绘制方法。 Override the JPanel paintComponent method. 重写JPanel paintComponent方法。

  3. I don't see your JFrame instantiation at all, but be sure to instantiate your JFrame with the SwingUtilities invokeLater method. 我根本看不到您的JFrame实例化,但是请确保使用SwingUtilities invokeLater方法实例化您的JFrame。

I'm not sure these tips will fix your problem, since you did not provide runnable code for any of us to test. 我不确定这些技巧是否可以解决您的问题,因为您没有提供可运行的代码供我们中的任何人测试。

将您的两个add()方法调用从paint()移到构造函数中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM