簡體   English   中英

我將鼠標懸停在它們上方后才顯示

[英]jbuttons only showing after i hover over them

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

謝謝!

這是我看到的問題。

  1. 在構造函數中讀取一次圖像,然后根據需要繪制多次。

  2. 不要重寫JPanel繪制方法。 重寫JPanel paintComponent方法。

  3. 我根本看不到您的JFrame實例化,但是請確保使用SwingUtilities invokeLater方法實例化您的JFrame。

我不確定這些技巧是否可以解決您的問題,因為您沒有提供可運行的代碼供我們中的任何人測試。

將您的兩個add()方法調用從paint()移到構造函數中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM