⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ui.java

📁 扫雷的源代码,包结构采用经典的MVC模式,包括模型、控制、视图三部分
💻 JAVA
字号:
/*
 * Created on Mar 24, 2005
 *
 * TODO the view of MVC structure. to create user interface and show result
 * automatically when model data are changed
 */
package view;

import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.HashMap;
import java.util.Observable;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;


import javax.swing.JSeparator;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.UIManager;

import model.CellNotifingObject;
import model.Location;
import model.Model;
import model.NotifingObject;
import model.SaveAndLoad;

import control.CoreAction;
import control.MenuAction;

import java.util.Observer;

/**
 * @author mqqqvpppm
 * 
 * TODO the view of MVC structure. to create user interface and show result
 * automatically when model data are changed
 */
public class UI implements Observer {

	public UI() {

	}

	public UI(Model model) {

		try {
			UIManager
					.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.model = model;

		componentsInstantiation();
		initComponents();
		mainFrame.setVisible(true);
	}

	public MyButton[][] getButtons() {
		return jLabelButtons;
	}

	public JFrame getMainFrame() {
		return mainFrame;
	}

	public JMenuItem getMenuItem(String name) {
		if (menuItemMap == null)
			return null;
		return (JMenuItem) menuItemMap.get(name);
	}

	public String[] getUserNames() {
		return userNames;
	}

	public int[] getScore() {
		return score;
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 */
	private void initComponents() {
		mainFrame
				.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		mainFrame.setResizable(false);

		//build menu bar

		group.add(easy);
		group.add(hard);
		group.add(hell);
		group.add(custom);

		game.setText("Game");
		startItem.setText("Start");
		game.add(startItem);
		startItem.addActionListener(menuListener);
		menuItemMap.put("start", startItem);
		game.add(jSeparator1);

		easy.setText("Easy");
		game.add(easy);
		easy.addActionListener(menuListener);
		menuItemMap.put("easy", easy);

		hard.setText("Hard");
		hard.addActionListener(menuListener);
		game.add(hard);
		menuItemMap.put("hard", hard);

		hell.setText("Hell");
		hell.addActionListener(menuListener);
		game.add(hell);
		menuItemMap.put("hell", hell);

		custom.setText("Custom");
		custom.addActionListener(menuListener);
		game.add(custom);
		menuItemMap.put("custom", custom);

		game.add(jSeparator2);

//		music.setText("Music");
//		music.setEnabled(false);
//		game.add(music);
//		menuItemMap.put("music", music);

		record.setText("Record");
		game.add(record);
		menuItemMap.put("record", record);
		record.addActionListener(menuListener);

		game.add(jSeparator3);

		language.setText("Language");
		english.setText("English");
		english.setEnabled(false);
		language.add(english);
		menuItemMap.put("english", english);

		chinese.setText("Chinese");
		chinese.setEnabled(false);
		language.add(chinese);
		menuItemMap.put("chinese", chinese);

		game.add(language);

		exit.setText("Exit");
		exit.addActionListener(menuListener);
		game.add(exit);
		menuItemMap.put("exit", exit);

		aJMenuBar.add(game);

		saveAndLoad.setText("Save/Load");

		save.setText("Save");
		save.addActionListener(menuListener);
		saveAndLoad.add(save);
		menuItemMap.put("save", save);

		load.setText("Load");
		load.addActionListener(menuListener);
		saveAndLoad.add(load);
		menuItemMap.put("load", load);

		aJMenuBar.add(saveAndLoad);

		help.setText("help");
//		contents.setText("Contents");
//		contents.setEnabled(false);
//		help.add(contents);
//		menuItemMap.put("contents", contents);

		about.setText("About");
		about.addActionListener(menuListener);
		help.add(about);
		menuItemMap.put("about", about);

		aJMenuBar.add(help);
		mainFrame.setJMenuBar(aJMenuBar);
		//build menu bar end

		mainFrame.getContentPane().setLayout(null);

		//build head panel
		head.setBorder(new javax.swing.border.TitledBorder(null, "",
				javax.swing.border.TitledBorder.CENTER,
				javax.swing.border.TitledBorder.DEFAULT_POSITION));
		head.setLayout(null);

		start.setIcon(Images.START_BEGIN);
		start.addActionListener(coreListener);

		Font font = new Font("Serif", Font.BOLD, 12);
		mineNumberLabel.setFont(font);
		time.setFont(font);

		mineNumberLabel.setHorizontalAlignment(JLabel.CENTER);
		time.setHorizontalAlignment(JLabel.CENTER);

		mineNumberLabel.setText(String.valueOf(model.getMineNumber()));
		time.setText("0");

		head.add(mineNumberLabel);
		head.add(start);
		head.add(time);

		mainFrame.getContentPane().add(head);
		//build head panel end

		//build body panel
		mainFrame.getContentPane().add(body);
		//build body panel end
		mainFrame.setTitle("JMineSweeper");
		//		Image mainFrameIcon = Images.createImage("images/mainFrameIcon.gif");
		//		if (mainFrameIcon != null)
		mainFrame.setIconImage(Images.FRAME_IMAGE);
		java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
				.getScreenSize();

		//build head, and body in detail
		restart(model.getWidth(), model.getHeight(), model.getMineNumber(),
				model.getType());

		mainFrame
				.setLocation((screenSize.width - head.getWidth()) / 2,
						(screenSize.height - aJMenuBar.getHeight()
								- head.getHeight() - body.getHeight()) / 2);

		mainFrame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				try {
					io.saveType();
					//					clearRecord();
					io.saveRecord(userNames, score);
					io.closeStream();
				} catch (IOException e1) {
				}
			}
		});

		try {
			io.loadRecord(userNames, score);
		} catch (IOException e1) {
			int i;
			int length = userNames.length;
			for (i = 0; i != length; i++) {
				userNames[i] = "Unknow Name";
				score[i] = 999;
			}
		}
	}

	//Instantiation of components
	private void componentsInstantiation() {
		mainFrame = new JFrame();
		head = new JPanel();
		body = new JPanel();
		//		mineNumberPanel = new JPanel();
		mineNumberLabel = new JLabel();
		//		startPanel = new JPanel();
		start = new JButton();
		//		timePanel = new JPanel();
		time = new JLabel();

		aJMenuBar = new JMenuBar();
		game = new JMenu();
		startItem = new JMenuItem();
		jSeparator3 = new JSeparator();
		//        easy = new JRadioButtonMenuItem();
		easy = new JCheckBoxMenuItem();
		hard = new JCheckBoxMenuItem();
		hell = new JCheckBoxMenuItem();
		custom = new JCheckBoxMenuItem();

		music = new JCheckBoxMenuItem();
		record = new JMenuItem();

		language = new JMenu();
		english = new JMenuItem();
		chinese = new JMenuItem();

		exit = new JMenuItem();
		saveAndLoad = new JMenu();
		save = new JMenuItem();
		jSeparator1 = new JSeparator();
		load = new JMenuItem();
		help = new JMenu();
		contents = new JMenuItem();
		jSeparator2 = new JSeparator();
		about = new JMenuItem();

		menuItemMap = new HashMap(15);
		coreListener = new CoreAction(model, this);
		menuListener = new MenuAction(model, this);

		group = new ButtonGroup();

		try {
			io = new SaveAndLoad(model);
		} catch (IOException e) {
			e.printStackTrace();
		}

		userNames = new String[3];
		score = new int[3];
	}

	public Model getModel() {
		return model;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	public void update(Observable o, Object arg) {
		//NotifingObject notifingObject = (NotifingObject)arg;

		int type = ((NotifingObject) arg).getType();

		switch (type) {
		case NotifingObject.TYPE_CELLCHANGED:
			Location location = ((CellNotifingObject) arg).getLocation();
			cellChanged(location);
			break;
		case NotifingObject.TYPE_RESTART:
			restart(model.getWidth(), model.getHeight(), model.getMineNumber(),
					model.getType());
			break;
		case NotifingObject.TYPE_GAMEOVER:
			gameOver();
			break;
		case NotifingObject.TYPE_WIN:
			win();
			break;
		case NotifingObject.TYPE_TIME:
			time.setText(String.valueOf(model.getTime()));
			//			System.out.println(model.getTime());
			break;
		default:
			break;
		}
	}

	private void win() {
		int type = model.getType();
		switch (type) {
		case Model.TYPE_EASY:
			if (score[0] > model.getTime()) {
				if (breakRecord == null) {
					breakRecord = new BreakRecordDialog(mainFrame,
							BreakRecordDialog.BREAK);
				}
				if (breakRecord.show(model.getTime())) {
					userNames[0] = breakRecord.getUserName();
					score[0] = model.getTime();
				}
			}
			break;
		case Model.TYPE_HARD:
			if (score[0] > model.getTime()) {
				if (breakRecord == null) {
					breakRecord = new BreakRecordDialog(mainFrame,
							BreakRecordDialog.BREAK);
				}
				if (breakRecord.show(model.getTime())) {
					userNames[1] = breakRecord.getUserName();
					score[1] = model.getTime();
				}
			}
			break;
		case Model.TYPE_HELL:
			if (score[0] > model.getTime()) {
				if (breakRecord == null) {
					breakRecord = new BreakRecordDialog(mainFrame,
							BreakRecordDialog.BREAK);
				}
				if (breakRecord.show(model.getTime())) {
					userNames[2] = breakRecord.getUserName();
					score[2] = model.getTime();
				}
			}
			break;
		default:
			System.out.println("ddd");
			new BreakRecordDialog(mainFrame, BreakRecordDialog.JUST_WIN)
					.show(model.getTime());
		}
	}

	private void restart(int width, int height, int mineNumber, int type) {

		if (this.width == width && this.height == height) {
			int x = 0;
			int y = 0;
			for (x = 0; x != width; ++x)
				for (y = 0; y != height; ++y)
					jLabelButtons[y][x].setIcon(Images.UNCLICKED);

			time.setText("0");
			mineNumberLabel.setText(String.valueOf(model.getMineNumber()));
			return;
		}

		this.width = width;
		this.height = height;
		mainFrame.remove(body);
		body = new JPanel();
		body.setLayout(null);
		jLabelButtons = new MyButton[height][width];
		int x = 0;
		int y = 0;
		MyButton button;
		for (y = 0; y != height; y++) {
			for (x = 0; x != width; x++) {
				jLabelButtons[y][x] = new MyButton(x, y);
				button = jLabelButtons[y][x];
				button.setBounds(bodyMarginOther + x * buttonSize,
						bodyMarginNorth + y * buttonSize, buttonSize,
						buttonSize);
				button.setIcon(Images.UNCLICKED);
				body.add(button);
				button.addMouseListener(coreListener);
			}
		}

		head.setBounds(4, 5, width * buttonSize + bodyMarginOther * 2 - 4, 65);
		start.setBounds((head.getWidth() - 50) / 2,
				(head.getHeight() - 50) / 2, 50, 50);
		mineNumberLabel.setBounds(0, 0, head.getHeight(), head.getHeight());
		time.setBounds(head.getWidth() - head.getHeight(), 0, head.getHeight(),
				head.getHeight());

		body.setBounds(2, head.getHeight(), width * buttonSize + 2
				* bodyMarginOther, height * buttonSize + bodyMarginNorth
				+ bodyMarginOther);
		body.setBorder(new javax.swing.border.TitledBorder(
				new javax.swing.border.TitledBorder(""), "Challenge Yourself!",
				javax.swing.border.TitledBorder.CENTER,
				javax.swing.border.TitledBorder.DEFAULT_POSITION));
		mainFrame.getContentPane().add(body);
		mainFrame.setSize(body.getWidth() + 10, body.getHeight()
				+ head.getHeight() + 60);
		mainFrame.validate();
		mainFrame.repaint();
		time.setText("0");
		mineNumberLabel.setText(String.valueOf(model.getMineNumber()));

		switch (type) {
		case Model.TYPE_EASY:
			easy.setSelected(true);
			break;
		case Model.TYPE_HARD:
			hard.setSelected(true);
			break;
		case Model.TYPE_HELL:
			hell.setSelected(true);
			break;
		case Model.TYPE_CUSTOM:
			custom.setSelected(true);
			break;
		}

	}

	private void cellChanged(Location location) {
		MyButton button = jLabelButtons[location.y][location.x];
		if (model.isClickedButton(location)) {
			if (model.isNumber(location)) {
				button.setIcon(Images.number[model.getValue(location) - 1]);
			} else {
				button.setIcon(Images.CLICKED);
			}
		} else if (model.isMark(location)) {
			button.setIcon(Images.MARKED);
		} else if (model.isMarkedMine(location)) {
			button.setIcon(Images.MARKED_MINE);
		} else {
			button.setIcon(Images.UNCLICKED);
		}
		mineNumberLabel.setText(String.valueOf(model.getMineNumber()
				- model.getMarkedMineNumber()));
	}

	private void gameOver() {
		Location location;

		for (int y = 0; y != height; ++y) {
			for (int x = 0; x != width; ++x) {

				location = new Location(x, y);
				if (model.isMine(location) && model.isClickedButton(location)) {
					jLabelButtons[y][x].setIcon(Images.MINE_BLAST);
				} else if (!model.isMine(location)
						&& model.isMarkedMine(location)) {
					jLabelButtons[y][x].setIcon(Images.MINE_WRONG);
				} else if (model.isMine(location)) {
					jLabelButtons[y][x].setIcon(Images.MINE);
				}
			}
		}
	}

	public void clearRecord() {
		int length = userNames.length;
		for (int i = 0; i != length; i++) {
			userNames[i] = "Unknow Name";
			score[i] = 999;
		}
	}

	//Variables declaration
	private final int buttonSize = 16;

	private final int bodyMarginNorth = 20;

	private final int bodyMarginOther = 12;

	private int width;

	private int height;

	private int intMineNumber;

	private int buttonNumber;

	private JMenuBar aJMenuBar;

	private JMenuItem about;

	private JPanel body;

	private JMenuItem chinese;

	private JMenuItem contents;

	private JCheckBoxMenuItem custom;

	private JCheckBoxMenuItem easy;

	//private JRadioButtonMenuItem easy;
	private JMenuItem english;

	private JMenuItem exit;

	private JMenu game;

	private JCheckBoxMenuItem hard;

	private JPanel head;

	private JCheckBoxMenuItem hell;

	private JMenu help;

	private JSeparator jSeparator1;

	private JSeparator jSeparator2;

	private JSeparator jSeparator3;

	private JMenu language;

	private JMenuItem load;

	private JLabel mineNumberLabel;

	//	private JPanel mineNumberPanel;

	private JCheckBoxMenuItem music;

	private JMenuItem record;

	private JMenuItem save;

	private JMenu saveAndLoad;

	private JButton start;

	private JMenuItem startItem;

	//	private JPanel startPanel;

	private JLabel time;

	//	private JPanel timePanel;

	private BreakRecordDialog breakRecord;

	private JFrame mainFrame;

	private MyButton[][] jLabelButtons;

	private ButtonGroup group;

	private Model model;

	private CoreAction coreListener;

	private MenuAction menuListener;

	private HashMap menuItemMap;

	private String[] userNames;

	private int[] score;

	private SaveAndLoad io;

	//End of variables declaration
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -