powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Кто как видит MVC на реальном примере шахматной доски и фигур?
4 сообщений из 4, страница 1 из 1
Кто как видит MVC на реальном примере шахматной доски и фигур?
    #37737089
_webdev_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Нарисовал доску шахматную, расставил фигуры и добавил парочку евентов.

Все старался сразу же делать по принципу MVC дабы набивать руку. Перечитал и сейчас и раньше десятки статей, вроде и принцип понимаю, а при программировании шаг влево, шаг вправо и тону.. :(
Так вот, вот черновой вариант трех классов, вот так вот сходу они мне написались.

1. Пожалуйста подкорректируйте как кто понимает это все?
2. И еще вопросик, припустим есть обычная форма - две кнопки и два поля для ввода - откуда высосать Model? Получается будет только интерфейс(View) и обработчик событий этой формы(Controller)?
3. И еще вопросик, тут вот мыслю подкинули(да я и сам понимаю), что такой код не есть хорошо...



Код: java
1.
Object chekPiece = ((JLabel) (((JComponent) evt.getComponent()).getComponent(0))).getIcon();


Альтернатива? Создавать временные переменные - будет больше кода, но читабельней...

Спасибо за советы - вот три класса!
Да конечно, кто-то может лучшую идею предложить как код написать и так д.. но я спрашиваю о архитектуре.

View
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
package chess.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ChessBoardView extends JPanel {

	private JPanel northInfoPanel = new JPanel(new GridLayout(1, 8));
	private JPanel southInfoPanel = new JPanel(new GridLayout(1, 8));
	private JPanel westInfoPanel = new JPanel(new GridLayout(8, 1));
	private JPanel eastInfoPanel = new JPanel(new GridLayout(8, 1));
	private JPanel centerBoardPanel = new JPanel(new GridLayout(8, 8));

	private String[] letterArray = new String[] { "            a",
			"            b", "            c", "            d", "            e",
			"            f", "            g", "            h" };

	private JPanel[][] countChessCells = new JPanel[8][8];

	private ChessBoardController chessBoardController;

	public ChessBoardView() {

		this.chessBoardController = new ChessBoardController();

		this.setLayout(new BorderLayout());
		drawNorthInfoPanel();
		drawSouthInfoPanel();
		drawChessBoard();
		drawEastInfoPanel();
		drawWestInfoPanel();
		this.chessBoardController.setChessBoardView(this);
		this.add(northInfoPanel, BorderLayout.NORTH);
		this.add(southInfoPanel, BorderLayout.SOUTH);
		this.add(centerBoardPanel, BorderLayout.CENTER);
		this.add(westInfoPanel, BorderLayout.WEST);
		this.add(eastInfoPanel, BorderLayout.EAST);
	}

	private void drawChessBoard() {
		for (int y = 0; y < 8; y++) {
			for (int x = 0; x < 8; x++) {
				countChessCells[y][x] = new JPanel(new BorderLayout());
				countChessCells[y][x].addMouseListener(this.chessBoardController);
				this.centerBoardPanel.add(countChessCells[y][x]);

				if (y % 2 == 0) {
					if (x % 2 != 0) {
						countChessCells[y][x].setBackground(Color.GRAY);
					} else {
						countChessCells[y][x].setBackground(Color.WHITE);
					}
				} else {
					if (x % 2 == 0) {
						countChessCells[y][x].setBackground(Color.GRAY);
					} else {
						countChessCells[y][x].setBackground(Color.WHITE);
					}
				}
			}
		}
	}

	private void drawNorthInfoPanel() {
		for (int i = 0; i < 8; i++) {
			this.northInfoPanel.add(new JLabel(letterArray[i]),
					BorderLayout.CENTER);
		}
	}

	private void drawSouthInfoPanel() {
		for (int i = 0; i < 8; i++) {
			this.southInfoPanel.add(new JLabel(letterArray[i]),
					BorderLayout.CENTER);
		}
	}

	private void drawEastInfoPanel() {
		for (int i = 8; i >= 1; i--) {
			this.eastInfoPanel.add(new JLabel(Integer.toString(i)),
					BorderLayout.CENTER);
		}
	}

	private void drawWestInfoPanel() {
		for (int i = 8; i >= 1; i--) {
			this.westInfoPanel.add(new JLabel(Integer.toString(i)),
					BorderLayout.CENTER);
		}
	}

	public JPanel[][] getCountChessCells() {
		return countChessCells;
	}

	public void setCountChessCells(JPanel[][] countChessCells) {
		this.countChessCells = countChessCells;
	}

}



Controller
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
package chess.ui;

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JComponent;
import javax.swing.JLabel;

public class ChessBoardController implements MouseListener{
	
	private ChessBoardView chessBoardView;
	
	private ChessBoardModel chessBoardModel;
	
	private JComponent mouseFocusComponent;
	private JComponent mousePressedComponent;
	
	public ChessBoardController() {
		
		this.chessBoardModel = new ChessBoardModel();
		
	}
	
	private void init(){
		arrangeChessPieces();
	}
	
	private void arrangeChessPieces() {

		for (int y = 0; y < 8; y++) {
			for (int x = 0; x < 8; x++) {
				this.chessBoardView.getCountChessCells()[y][x].add(
						this.getPieceObject(this.chessBoardModel.getStrChessBoard()[y][x]),
						BorderLayout.CENTER);
				this.chessBoardView.getCountChessCells()[y][x].validate();
			}
		}
	}

	private JLabel getPieceObject(String strPieceName) {

		JLabel temPieceLabel;

		if (strPieceName.equals("RB"))
			temPieceLabel = new JLabel(this.chessBoardModel.getRookBlack());
		else if (strPieceName.equals("BB"))
			temPieceLabel = new JLabel(this.chessBoardModel.getBishopBlack());
		else if (strPieceName.equals("NB"))
			temPieceLabel = new JLabel(this.chessBoardModel.getKnightBlack());
		else if (strPieceName.equals("QB"))
			temPieceLabel = new JLabel(this.chessBoardModel.getQueenBlack());
		else if (strPieceName.equals("KB"))
			temPieceLabel = new JLabel(this.chessBoardModel.getKingBlack());
		else if (strPieceName.equals("PB"))
			temPieceLabel = new JLabel(this.chessBoardModel.getPawnBlack());
		else if (strPieceName.equals("RW"))
			temPieceLabel = new JLabel(this.chessBoardModel.getRookWhite());
		else if (strPieceName.equals("BW"))
			temPieceLabel = new JLabel(this.chessBoardModel.getBishopWhite());
		else if (strPieceName.equals("NW"))
			temPieceLabel = new JLabel(this.chessBoardModel.getKnightWhite());
		else if (strPieceName.equals("QW"))
			temPieceLabel = new JLabel(this.chessBoardModel.getQueenWhite());
		else if (strPieceName.equals("KW"))
			temPieceLabel = new JLabel(this.chessBoardModel.getKingWhite());
		else if (strPieceName.equals("PW"))
			temPieceLabel = new JLabel(this.chessBoardModel.getPawnWhite());
		else
			temPieceLabel = new JLabel();
		return temPieceLabel;
	}

	private String getPieceName(String chessIconPath) {
		int start = 28;
		int end = chessIconPath.length() - 4;
		String pieceName = chessIconPath.substring(start, end);
		return pieceName;
	}
	
	@Override
	public void mouseClicked(MouseEvent evt) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent evt) {
		if (((JComponent) evt.getComponent()).getBackground() != this.chessBoardModel.getMousePressedColor())
			this.chessBoardModel.setTempMouseEnteredComponentColor(((JComponent) evt
					.getComponent()).getBackground());
		if ((JComponent) evt.getSource() != this.mousePressedComponent) {
			this.mouseFocusComponent = (JComponent) evt.getComponent();
			this.chessBoardModel.setTempMouseFocusComponentColor(this.mouseFocusComponent
					.getBackground());
			this.mouseFocusComponent.setBackground(this.chessBoardModel.getMouseEnteredColor());
		}
	}

	@Override
	public void mouseExited(MouseEvent evt) {
		if ((JComponent) evt.getSource() != this.mousePressedComponent)
			this.mouseFocusComponent
					.setBackground(this.chessBoardModel.getTempMouseFocusComponentColor());
	}

	@Override
	public void mousePressed(MouseEvent evt) {
		
		Object chekPiece = ((JLabel) (((JComponent) evt.getComponent())
				.getComponent(0))).getIcon();
		
		if (chekPiece != null) {
			System.out.println(getPieceName(chekPiece.toString()));
		} else {
			System.out.println("Zero");
		}
		
		if (this.mousePressedComponent == null) {
			this.mousePressedComponent = (JComponent) evt.getComponent();
			this.chessBoardModel.setTempMousePressedComponentColor(this.chessBoardModel.getTempMouseEnteredComponentColor());
			this.mousePressedComponent.setBackground(this.chessBoardModel.getMousePressedColor());
		} else {
			if (((JComponent) evt.getComponent()).getBackground() != this.chessBoardModel.getMousePressedColor()) {
				this.mousePressedComponent
						.setBackground(this.chessBoardModel.getTempMousePressedComponentColor());
				this.chessBoardModel.setTempMousePressedComponentColor(this.chessBoardModel.getTempMouseEnteredComponentColor());
				this.mousePressedComponent = (JComponent) evt.getComponent();
				this.mousePressedComponent
						.setBackground(this.chessBoardModel.getMousePressedColor());
			} else {
				this.mousePressedComponent
						.setBackground(chessBoardModel.getTempMousePressedComponentColor());
			}
		}

	}

	@Override
	public void mouseReleased(MouseEvent evt) {
		// mouseFocusComponent.setBackground(mouseEnteredColor);

	}

	public void setChessBoardView(ChessBoardView chessBoardView) {
		this.chessBoardView = chessBoardView;
		init();
	}

}



Model
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
package chess.ui;

import java.awt.Color;

import javax.swing.ImageIcon;

public class ChessBoardModel {

	private Color mouseEnteredColor = new Color(200, 230, 255);
	private Color tempMouseFocusComponentColor;
	private Color tempMousePressedComponentColor;
	private Color tempMouseEnteredComponentColor;
	private Color mousePressedColor = new Color(255, 150, 150);

	private ImageIcon rookBlack = new ImageIcon(
			"./lib/images/ChessFigurPack/rookBlack.png");
	private ImageIcon rookWhite = new ImageIcon(
			"./lib/images/ChessFigurPack/rookWhite.png");
	private ImageIcon bishopBlack = new ImageIcon(
			"./lib/images/ChessFigurPack/bishopBlack.png");
	private ImageIcon bishopWhite = new ImageIcon(
			"./lib/images/ChessFigurPack/bishopWhite.png");
	private ImageIcon knightBlack = new ImageIcon(
			"./lib/images/ChessFigurPack/knightBlack.png");
	private ImageIcon knightWhite = new ImageIcon(
			"./lib/images/ChessFigurPack/knightWhite.png");
	private ImageIcon kingBlack = new ImageIcon(
			"./lib/images/ChessFigurPack/kingBlack.png");
	private ImageIcon kingWhite = new ImageIcon(
			"./lib/images/ChessFigurPack/kingWhite.png");
	private ImageIcon queenBlack = new ImageIcon(
			"./lib/images/ChessFigurPack/queenBlack.png");
	private ImageIcon queenWhite = new ImageIcon(
			"./lib/images/ChessFigurPack/queenWhite.png");
	private ImageIcon pawnBlack = new ImageIcon(
			"./lib/images/ChessFigurPack/pawnBlack.png");
	private ImageIcon pawnWhite = new ImageIcon(
			"./lib/images/ChessFigurPack/pawnWhite.png");

	private String[][] strChessBoard = new String[][] {
			{ "RB", "NB", "BB", "QB", "KB", "BB", "NB", "RB" },
			{ "PB", "PB", "PB", "PB", "PB", "PB", "PB", "PB" },
			{ "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  " },
			{ "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  " },
			{ "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  " },
			{ "  ", "  ", "  ", "  ", "  ", "  ", "  ", "  " },
			{ "PW", "PW", "PW", "PW", "PW", "PW", "PW", "PW" },
			{ "RW", "NW", "BW", "QW", "KW", "BW", "NW", "RW" } };

	public Color getMouseEnteredColor() {
		return mouseEnteredColor;
	}

	public Color getTempMouseFocusComponentColor() {
		return tempMouseFocusComponentColor;
	}

	public Color getTempMousePressedComponentColor() {
		return tempMousePressedComponentColor;
	}

	public Color getTempMouseEnteredComponentColor() {
		return tempMouseEnteredComponentColor;
	}

	public Color getMousePressedColor() {
		return mousePressedColor;
	}

	public ImageIcon getRookBlack() {
		return rookBlack;
	}

	public ImageIcon getRookWhite() {
		return rookWhite;
	}

	public ImageIcon getBishopBlack() {
		return bishopBlack;
	}

	public ImageIcon getBishopWhite() {
		return bishopWhite;
	}

	public ImageIcon getKnightBlack() {
		return knightBlack;
	}

	public ImageIcon getKnightWhite() {
		return knightWhite;
	}

	public ImageIcon getKingBlack() {
		return kingBlack;
	}

	public ImageIcon getKingWhite() {
		return kingWhite;
	}

	public ImageIcon getQueenBlack() {
		return queenBlack;
	}

	public ImageIcon getQueenWhite() {
		return queenWhite;
	}

	public ImageIcon getPawnBlack() {
		return pawnBlack;
	}

	public ImageIcon getPawnWhite() {
		return pawnWhite;
	}

	public String[][] getStrChessBoard() {
		return strChessBoard;
	}

	public void setTempMouseFocusComponentColor(
			Color tempMouseFocusComponentColor) {
		this.tempMouseFocusComponentColor = tempMouseFocusComponentColor;
	}

	public void setTempMousePressedComponentColor(
			Color tempMousePressedComponentColor) {
		this.tempMousePressedComponentColor = tempMousePressedComponentColor;
	}

	public void setTempMouseEnteredComponentColor(
			Color tempMouseEnteredComponentColor) {
		this.tempMouseEnteredComponentColor = tempMouseEnteredComponentColor;
	}

}
...
Рейтинг: 0 / 0
Кто как видит MVC на реальном примере шахматной доски и фигур?
    #37737146
Фотография Blazkowicz
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Кроме MVC существуют разные вариации, например MVP и производные.
MVC лучше подходит для web. MVP - для GUI.
Архитектура Swing, не совсем MVC ( http://java.sun.com/products/jfc/tsc/articles/architecture/) - можно придерживаться её.

Model вообще не годится никуда. Там не должно быть никаких Color и ImageIcon. Модель (для Swing) желательно делать на JavaBeans: POJO, свойства, энумы, propertyChangeListener-ы

Фигуры - объекты со своим поведением. Black/White это свойство\тип объекта. К java.awt.Color никакого отношения не имеет. А если у меня "под дерево" рендеринг? Доску тоже стоит делать полноценным объектом, а не массивом. Почему два пробела эта пустая клетка?

В GUI контроллер часто привязывается к компаненте. Хранить его отдельно смысла особого нет. Есть ещё такая хорошая технология - Binding.

В целом, косяков масса. По поводу именно MVC - Model отодрать от Swing\AWT. Контроллер поместить в компаненту.
...
Рейтинг: 0 / 0
Кто как видит MVC на реальном примере шахматной доски и фигур?
    #37741220
_webdev_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Как говорится - у меня говнокод. :(
Вот, начал с самого простого.
Сделал три класса при клике на кнопочку увеличивать коунтер. У меня опять масса вопросов. :(
Начитался статей, вики и в голове каламбур, а реально простого примера найти не могу, думаю это будет самый простой.

1. Что следует создавать первым? Сontroller или View?
2. Если Controller, то как тогда передавать евент кнопки на обратобку?
3. Дополните пожалуйста пример несколькими строчками, чтоб получилась MVC архитектура, я хочу это увидеть на этом примере, надеюсь наконец ко мне дойдет!! А то в теории понимаю, а на практике ступор. :(

Main
Код: java
1.
2.
3.
4.
5.
6.
7.
public class Main {

	public static void main(String[] args) {
		new MVC_Controller();

	}
}


MVC_Controller
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MVC_Controller implements ActionListener {

	private MVC_View view;
	private MVC_Model model;

	public MVC_Controller() {
		this.view = new MVC_View();
		this.model = new MVC_Model();
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		if (evt.getSource() == "Click")
			System.out.println();
	}

}


MVC_View
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class MVC_View {

	private JFrame frame;

	private final int frameWidth = 150;
	private final int frameHeight = 150;

	private JButton button;
	private JTextField field;

	public MVC_View() {
		this.frame = new JFrame();
		this.frame.setTitle("MVC");
		this.frame.setSize(this.frameWidth, this.frameHeight);
		this.frame.setLocationRelativeTo(null);
		this.frame.setLayout(new FlowLayout());
		this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		init();

		this.frame.setVisible(true);
	}

	private void init() {

		this.button = new JButton("Ckick");
		this.field = new JTextField("0", 5);

		this.frame.add(field);
		this.frame.add(button);

		// this.button.addActionListener();
		// this.field.addActionListener();
	}
}


MVC_Model
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
public class MVC_Model {

	private int counter = 0;

	public MVC_Model() {

	}

	public int getCounter() {
		return counter;
	}

	public void setCounter(int counter) {
		this.counter = counter;
	}

}



Если что, вот проект на Eclipse - http://dl.dropbox.com/u/26399837/MVC1.rar
СПАСИБО!
...
Рейтинг: 0 / 0
Кто как видит MVC на реальном примере шахматной доски и фигур?
    #37742369
_webdev_
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Копал, копал и вроде докопался... А как такой пример? Присутствует или виден здесь MVC? Спасибо!

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
import java.awt.FlowLayout;

import javax.swing.JFrame;

public class Main {
	
	private JFrame frame;

	private final int frameWidth = 180;
	private final int frameHeight = 150;
	
	public static void main(String[] args) {
		
		MVC_Model model = new MVC_Model();
		
		new Main(model);
	}
	
	public Main(MVC_Model model) {
		MVC_View view = new MVC_View(model);
		model.addMVCListener(view);
		this.frame = new JFrame();
		this.frame.setTitle("MVC");
		this.frame.setSize(this.frameWidth, this.frameHeight);
		this.frame.setLocationRelativeTo(null);
		this.frame.setLayout(new FlowLayout());
		this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		this.frame.add(view);
		
		this.frame.setVisible(true);
	}
}



Код: java
1.
2.
3.
4.
public interface I_MVC_Listener {

	public void valueChanged(MVC_Model model);
}



Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
public class MVC_Model {

	private int counter = 0;
	private I_MVC_Listener listener;

	public MVC_Model() {

	}

	public int getCounter() {
		return counter;
	}

	public void setCounter(int counter) {
		this.counter = counter;
	}

	public void addMVCListener(I_MVC_Listener l) {
		this.listener = l;
	}

	public void counterPlusPlus() {
		this.counter += 1;
		fireModelChanged();
	}

	private void fireModelChanged() {
		this.listener.valueChanged(this);
	}

}



Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MVC_View extends JPanel implements I_MVC_Listener {

	private JButton button;
	private JTextField field;

	private MVC_Model model;
	private MVC_Controller controller;

	public MVC_View(MVC_Model model) {

		this.model = model;
		this.model.addMVCListener(this);

		this.controller = new MVC_Controller(this.model);

		init();

		valueChanged(model);
	}

	private void init() {

		this.button = new JButton("Ckick");
		this.field = new JTextField("0", 5);

		this.add(field);
		this.add(button);

		this.button.addActionListener(this.controller);
		this.field.addActionListener(this.controller);
	}

	@Override
	public void valueChanged(MVC_Model model) {
		this.field.setText(Integer.toString(model.getCounter()));
	}
}


Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MVC_Controller implements ActionListener {

	private MVC_Model model;

	public MVC_Controller(MVC_Model model) {

		this.model = model;
	}

	@Override
	public void actionPerformed(ActionEvent evt) {
		model.counterPlusPlus();
	}
}
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Кто как видит MVC на реальном примере шахматной доски и фигур?
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]