简体   繁体   中英

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. 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. Override the JPanel paintComponent method.

  3. I don't see your JFrame instantiation at all, but be sure to instantiate your JFrame with the SwingUtilities invokeLater method.

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()移到构造函数中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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