2013-10-11 158 views
-1

我試圖將我的屏幕背景顏色設置爲綠色。未在Java中設置背景顏色

到目前爲止我的代碼:

package game; 

import java.awt.*; 
import javax.swing.JFrame; 


public class Game extends JFrame { 

    public static void main(String[] args) { 
     DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN); 
     Game g = new Game(); 
     g.run(dm); 

    } 

    public void run(DisplayMode dm) { 
     setBackground(Color.GREEN); 
     setForeground(Color.WHITE); 
     setFont(new Font("arial", Font.PLAIN, 24)); 
     Screen s = new Screen(); 

     try { 
      s.setFullScreen(dm, this); 
      try { 
       Thread.sleep(5000); 
      } catch (Exception E) { 
      } 
     } finally { 
      s.restoreScreen(); 
     } 
    } 

    @Override 
    public void paint(Graphics g){ 
     g.drawString("Check Screen", 200, 200); 
    } 
} 

當我運行程序時,我得到這個:

setBackground(Color.GREEN); 

printScreen

屏幕應根據線是綠色的爲什麼運行該程序時背景未設置爲綠色?

+1

您是否嘗試過'this.getContentPane().setBackground(Color.GREEN)'? – Laf

+0

你說它的方式,你似乎想要將屏幕設置爲綠色,但是您將代碼中的JFrame設置爲綠色。 – user2277872

+1

參見[答案同樣的問題已經問] [1] [1]:http://stackoverflow.com/questions/2742270/jframe-setbackground-not-working-why – Samhain

回答

1

您需要在paint()方法中添加對super.paint (g);的調用。

@Override 
public void paint(Graphics g){ 
    super.paint (g); 
    g.drawString("Check Screen", 200, 200); 
} 

這將確保組件將正確繪製自己,包括背景顏色,然後繪製文本。

1

通常,整個方法非常糟糕。即使它與getContentPane().setBackground(Color.GREEN)一起使用,它也不會起作用,因爲您在EDT上撥打Thread.sleep(5000)(或者您將在短期或之後發生問題)。使用正確的組件重複任務(刷新屏幕):Swing Timer

而不是覆蓋JFrame'spaint方法,它是好得多使用JPanel並覆蓋它的paintComponent方法。所以,這樣的事情:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 


public class Game extends JFrame { 

    JFrame frame = new JFrame(); 

    public Game() { 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new Panel()); 
     frame.pack(); 
     frame.setVisible(true); 

    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new Game(); 
      } 
     }); 
    } 

    class Panel extends JPanel { 
     Timer timer; 

     Panel() { 
      setBackground(Color.BLACK); 
      setForeground(Color.WHITE); 
      refreshScreen(); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.setFont(new Font("arial", Font.PLAIN, 24)); 
      g.drawString("Check Screen", 200, 200); 
     } 

     public void refreshScreen() { 
      timer = new Timer(0, new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent e) { 
        repaint(); 
       } 
      }); 
      timer.setRepeats(true); 
      //Aprox. 60 FPS 
      timer.setDelay(17); 
      timer.start(); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(650, 480); 
     } 
    } 

}