2012年6月12日 星期二

Java Game Development(16) - Updating Display and Restore Screen


import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;

public class ScreenManager {

private GraphicsDevice vc;
//訪問顯示器屏幕
public ScreenManager(){
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = e.getDefaultScreenDevice();
}
//得到所有兼容
public DisplayMode[] getCompatibleDisplayMode(){ → Build-in Method
return vc.getDisplayModes();
}

//比較DisplayMode傳遞到vc,看它們是否匹配(boolean)
public DisplayMode findFirstCompatibleMode(DisplayMode modes[]){
DisplayMode goodModes[] = vc.getDisplayModes();
for(int x=0;x<modes.length;x++){ 循環DisplayMode列陣
for(int y=0;y<goodModes.length;y++){ 循環DisplayMode列陣
if(displayModesMatch(modes[x], goodModes[y])){
return modes[x];
}
}
}
return null;
}
//得到當前DisplayMode
public DisplayMode getCurrentDisplayMode(){
return vc.getDisplayMode();
}

//檢查兩種模式是否相互匹配
public boolean displayModesMatch(DisplayMode m1,DisplayMode m2){
if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
return false;
}
if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()) {
return false;
}
if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()) {
return false;
}
return true;
}
//全屏幕
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true);
f.setIgnoreRepaint(true);
f.setResizable(false);
vc.setFullScreenWindow(f);

if(dm != null && vc.isDisplayChangeSupported()) {
try{
vc.setDisplayMode(dm);
}catch(Exception e) {System.out.println("");}
}
f.createBufferStrategy(2); 兩個不同緩衝區中使用顯示器
}
//我們將設置圖形對象
public Graphics2D getGraphics() {
Window w = vc.getFullScreenWindow();
if(w != null) {
BufferStrategy s = w.getBufferStrategy();
return (Graphics2D)s.getDrawGraphics();
}
else {
return null;
}
}

//更新顯示
public void update() {
Window w = vc.getFullScreenWindow();
if(w != null) {
BufferStrategy s = w.getBufferStrategy();
if(!s.contentsLost()) { 如果內容不丟失
s.show();
}
}
}
//返回全屏窗口
public Window getFullScreenWindow() {
return vc.getFullScreenWindow();
}


//得到寬度
public int getWidth() {
Window w = vc.getFullScreenWindow();
if(w != null) {
return w.getWidth();
}
else {
return 0;
}
}


//得到高度
public int getHeight() {
Window w = vc.getFullScreenWindow();
if(w != null) {
return w.getHeight();
}
else {
return 0;
}
}

//獲得全屏
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if(w != null) {
w.dispose();
vc.setFullScreenWindow(null);
}
}


}

沒有留言:

張貼留言