powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Помочь новичку в проектировании классов
12 сообщений из 12, страница 1 из 1
Помочь новичку в проектировании классов
    #38727373
Denyss
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Всем привет, изучаю java и не могу понять, как правильно спроектировать класс.
Перейдем к сути:
1. Я имею Field extends JFrame и в нем есть несколько JLabel и JTextField .
2. В каждом JTextField есть @Override mouseReleased (MouseEvent evt).
3. У меня реализован метод SetValueToLableFromEachTextFieldWithCondition в Field - берется значения с каждого JTextField, агрегируем и вставляем в один из JLabel.

Как мне вызывать SetValueToLableFromEachTextFieldWithCondition в mouseReleased?

Какую литературу почитать, что бы больше не возникали такие тупые вопросы?
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38727507
avp.mk
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
DenyssКак мне вызывать SetValueToLableFromEachTextFieldWithCondition в mouseReleased?
Просто взять и вызывать..

Main.java
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
package wtf;

import static javax.swing.JFrame.EXIT_ON_CLOSE;
import static javax.swing.SwingUtilities.invokeLater;

public class Main {

    public static void main(String[] args) {
        invokeLater(new Runnable() {
            @Override public void run() {
                MainFrame frame = new MainFrame();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

MainFrame.java
Код: 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.
package wtf;

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import static wtf.Util.asArray;
import static wtf.Util.copyText_withSuffix;
import static wtf.Util.newJTextField;

/** Бывший Field */
public class MainFrame extends JFrame {

    private final MouseListener onMouseReleased = new MouseAdapter() {
        @Override public void mouseReleased(MouseEvent e) {
            //берёшь и вызываешь
            setValueToLabelFromEachTextField_withCondition();
        }
    };

    private final JLabel
            labA = new JLabel("A"),
            labB = new JLabel("B"),
            labC = new JLabel("C");

    private final JTextField
            // ActionListener не лучше ли подходит?
            tfA = newJTextField("A", onMouseReleased), 
            tfB = newJTextField("B", onMouseReleased),
            tfC = newJTextField("C", onMouseReleased);

    private final JTextField[] fields = {tfA, tfB, tfC};

    public MainFrame() {
        setLayout(new GridLayout(2, 3));
        for (Component c : asArray(labA, labB, labC, tfA, tfB, tfC)) { add(c); }
        setSize(320, 240);
        setLocationRelativeTo(null);
    }

    public void setValueToLabelFromEachTextField_withCondition() {
        //<editor-fold defaultstate="collapsed" desc="мегапроцессинг, меняющий все label'ы">
        int wholeLength = 0;
        for (JTextField field : fields) {
            wholeLength += field.getText().length();
        }
        String processedText = " (" + wholeLength + ")";
        copyText_withSuffix(tfA, labA, processedText);
        copyText_withSuffix(tfB, labB, processedText);
        copyText_withSuffix(tfC, labC, processedText);
        //</editor-fold>
    }
}

Util.java
Код: 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.
package wtf;

import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

public class Util {

    public static <T> T[] asArray(T... elements) { return elements; }

    public static void copyText_withSuffix(JTextComponent from, JLabel to, String suffix) {
        to.setText(from.getText() + suffix);
    }

    public static JTextField newJTextField(String text, MouseListener mouseListener) {
        JTextField textField = new JTextField(text);
        textField.addMouseListener(mouseListener);
        return textField;
    }

    public static JTextField newJTextField(String text, ActionListener actionListener) {
        JTextField textField = new JTextField(text);
        textField.addActionListener(actionListener);
        return textField;
    }
}

...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38727633
Denyss
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
avp.mk, спасибо что потратил время на меня, но правда мне не совсем понятно как это сделать в моей ситуации:
BattleshipFrame.java
Код: 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.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
package BattleshipFrame;

import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;

public class BattleshipFrame extends JFrame {

    public final Color colorBlue = new Color(0, 204, 255);
    public final Color colorBBB = new Color(35, 45, 55);
    public final static int cellSize = 40;
    public final static int hulfCellSize = cellSize / 2;
    public final static int thirdCellSize = cellSize / 3;
    public final static int quarterCellSize = cellSize / 4;
    public final static int fieldSize = 10;
    public final static int shipTopLineY = cellSize * (fieldSize + 2) + hulfCellSize;
    private myLabel mainLabel, ship4Label, ship3Label, ship2Label, ship1Label;
    private Field myField;
    private Field enemysField;
    private Ship ship4_1, ship3_1, ship3_2,
            ship2_1, ship2_2, ship2_3,
            ship1_1, ship1_2, ship1_3, ship1_4;
    public Container contentPane = getContentPane();

    public BattleshipFrame() {
        initComponents();
        setVisible(true);
    }

    private void initComponents() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMinimumSize(new java.awt.Dimension(1000, 720));
        setTitle("BattleShip Game");
        setResizable(false);
        contentPane.setLayout(null);

        mainLabel = new myLabel(0, 0, getWidth(), cellSize, "! text text text text text text text text !");
        ship4Label = new myLabel(0, shipTopLineY, cellSize, cellSize, "1 pcs.");
        ship3Label = new myLabel(cellSize * 5, shipTopLineY, cellSize, cellSize, "2 pcs.");
        ship2Label = new myLabel(cellSize * 9, shipTopLineY, cellSize, cellSize, "3 pcs.");
        ship1Label = new myLabel(cellSize * 12, shipTopLineY, cellSize, cellSize, "4 pcs.");

        ship4_1 = new Ship(cellSize,
                shipTopLineY,
                cellSize,
                cellSize * 4);

        ship3_1 = new Ship(cellSize * 6,
                shipTopLineY,
                cellSize,
                cellSize * 3);

        ship3_2 = new Ship(cellSize * 6,
                shipTopLineY,
                cellSize,
                cellSize * 3);

        ship2_1 = new Ship(cellSize * 10,
                shipTopLineY,
                cellSize,
                cellSize * 2);

        ship2_2 = new Ship(cellSize * 10,
                shipTopLineY,
                cellSize,
                cellSize * 2);

        ship2_3 = new Ship(cellSize * 10,
                shipTopLineY,
                cellSize,
                cellSize * 2);

        ship1_1 = new Ship(cellSize * 13,
                shipTopLineY,
                cellSize,
                cellSize);

        ship1_2 = new Ship(cellSize * 13,
                shipTopLineY,
                cellSize,
                cellSize);

        ship1_3 = new Ship(cellSize * 13,
                shipTopLineY,
                cellSize,
                cellSize);

        ship1_4 = new Ship(cellSize * 13,
                shipTopLineY,
                cellSize,
                cellSize);

        myField = new Field(0,
                cellSize,
                1 + cellSize * (fieldSize + 1),
                1 + cellSize * (fieldSize + 1),
                colorBlue);

        enemysField = new Field(getWidth() - cellSize * (fieldSize + 1) - hulfCellSize,
                cellSize,
                1 + cellSize * (fieldSize + 1),
                1 + cellSize * (fieldSize + 1),
                colorBBB);

        contentPane.add(mainLabel);
        contentPane.add(ship4Label);
        contentPane.add(ship3Label);
        contentPane.add(ship2Label);
        contentPane.add(ship1Label);
        contentPane.add(ship4_1);
        contentPane.add(ship3_1);
        contentPane.add(ship3_2);
        contentPane.add(ship2_1);
        contentPane.add(ship2_2);
        contentPane.add(ship2_3);
        contentPane.add(ship1_1);
        contentPane.add(ship1_2);
        contentPane.add(ship1_3);
        contentPane.add(ship1_4);
        contentPane.add(myField);
        contentPane.add(enemysField);
    }

    public void refreshNumberOfShips() {
        Ship[] arr;

        arr = new Ship[1];
        arr[0] = ship4_1;
        ship4Label.setNumberOfShips(getNumberOfShips(arr));

        arr = new Ship[2];
        arr[0] = ship3_1;
        arr[1] = ship3_2;
        ship3Label.setNumberOfShips(getNumberOfShips(arr));

        arr = new Ship[3];
        arr[0] = ship2_1;
        arr[1] = ship2_2;
        arr[2] = ship2_3;
        ship2Label.setNumberOfShips(getNumberOfShips(arr));

        arr = new Ship[4];
        arr[0] = ship1_1;
        arr[1] = ship1_2;
        arr[2] = ship1_3;
        arr[3] = ship1_4;
        ship1Label.setNumberOfShips(getNumberOfShips(arr));
    }

    private int getNumberOfShips(Ship[] arrShips) {
        int numberOfShips = 0;
        for (Ship ship : arrShips) {
            if (isShipOnPosition(ship)) {
                numberOfShips++;
            }
        }
        return numberOfShips;
    }

    private boolean isShipOnPosition(Ship ship) {
        return ship.startX == ship.getX() && ship.startY == ship.getY();
    }

}


Ship.java
Код: 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.
package BattleshipFrame;

import static BattleshipFrame.BattleshipFrame.cellSize;
import static BattleshipFrame.BattleshipFrame.hulfCellSize;
import static BattleshipFrame.BattleshipFrame.thirdCellSize;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import static javax.swing.BorderFactory.createMatteBorder;
import javax.swing.JTextField;

class Ship extends JTextField{

    private Point pointMouse;
    private final Color colorPink = new Color(204, 204, 255);
    private final Color colorGrey = new Color(51, 51, 51);
    public int startX, startY, height, width;
    
    public Ship(int x, int y, int w, int h) {
        init();
        startX = x;
        startY = y;
        height = h / cellSize;
        width = w / cellSize;
        setBounds(startX, startY, w, h);
    }
    
    private void init() {
        setEditable(false);
        setBackground(colorPink);
        setBorder(createMatteBorder(1, 1, 1, 1, colorGrey));
        setDragEnabled(true);
        
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    if (startX == getX() && startY == getY()) {
                        int tmp;
                        setBounds(getX(), getY(), getHeight(), getWidth());
                        tmp = height;
                        height = width;
                        width = tmp;
                    }
                }
            }
            
            @Override
            public void mousePressed(MouseEvent evt) {
                pointMouse = getMousePosition();
            }
            
            @Override
            public void mouseReleased(MouseEvent evt) {
                int x = getX() + evt.getX() - pointMouse.x;
                int y = getY() + evt.getY() - pointMouse.y;
                if (isPointOnField(x, y)) {
                    setLocation(getPointOnMyField(x, y));
                } else {
                    setLocation(startX, startY);
                }
            }
        });
        
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent evt) {
                setLocation(getPointOnMyField(getX() + evt.getX() - pointMouse.x,
                                              getY() + evt.getY() - pointMouse.y));
            }
        });
    
    }
    
    private boolean isPointOnField(int x, int y) {
        return cellSize - thirdCellSize <= x &&
               cellSize * 2 - thirdCellSize <= y &&
               cellSize * (11 - width) + thirdCellSize >= x &&
               cellSize * (12 - height) + thirdCellSize >= y;
    }
    
    private Point getPointOnMyField (int x, int y) {
        Point point = new Point(x, y);
        if (isPointOnField(point.x, point.y)) {
            int modX = point.x % cellSize;
            if (modX > hulfCellSize) {
                point.setLocation(point.x + cellSize - modX, point.y);
            } else {
                point.setLocation(point.x - modX, point.y);
            }
            
            int modY = point.y % cellSize;
            if (modY > hulfCellSize) {
                point.setLocation(point.x, point.y + cellSize - modY);
            } else {
                point.setLocation(point.x, point.y - modY);
            }
        }
        return point;
    }
    
}



Мне нужно вызвать refreshNumberOfShips (обновить Labels) при изменении позиции Ship в mouseReleased. Я пробовал перенести реализацию mouseReleased с Ship в BattleshipFrame, но я тогда не могу использовать методы и свойства Ship.

Как быть?
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38727944
avp.mk
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
DenyssМне нужно вызвать refreshNumberOfShips (обновить Labels) при изменении позиции Ship в mouseReleased. Я пробовал перенести реализацию mouseReleased с Ship в BattleshipFrame, но я тогда не могу использовать методы и свойства Ship.
Вот так можно (см. Ship.java стр. 51).

Main.java
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
package battleship;

import static javax.swing.JFrame.EXIT_ON_CLOSE;
import static javax.swing.SwingUtilities.invokeLater;

public class Main {

    public static void main(String[] args) {
        invokeLater(() -> {
            BattleshipFrame frame = new BattleshipFrame();
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

BattleshipFrame.java
Код: 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.
package battleship;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.JFrame;

public class BattleshipFrame extends JFrame {

    private static final Color
            COLOR_MY    = new Color(0, 204, 255),
            COLOR_ENEMY = new Color(35, 45, 55);

    public final static int
            CELL_SIZE         = 40,
            HALF_CELL_SIZE    = CELL_SIZE / 2,
            THIRD_CELL_SIZE   = CELL_SIZE / 3,
            QUARTER_CELL_SIZE = CELL_SIZE / 4,
            FIELD_SIZE        = 10,
            SHIP_TOP_LINE_Y   = CELL_SIZE * (FIELD_SIZE + 2) + HALF_CELL_SIZE;

    private final YourLabel mainLabel;

    private final YourLabel
            ship4Label = new YourLabel(0, SHIP_TOP_LINE_Y, CELL_SIZE, CELL_SIZE, "1 pcs."),
            ship3Label = new YourLabel(CELL_SIZE * 5, SHIP_TOP_LINE_Y, CELL_SIZE, CELL_SIZE, "2 pcs."),
            ship2Label = new YourLabel(CELL_SIZE * 9, SHIP_TOP_LINE_Y, CELL_SIZE, CELL_SIZE, "3 pcs."),
            ship1Label = new YourLabel(CELL_SIZE * 12, SHIP_TOP_LINE_Y, CELL_SIZE, CELL_SIZE, "4 pcs.");

    private final Field myField = new Field(0, CELL_SIZE, 1 + CELL_SIZE * (FIELD_SIZE + 1), 1 + CELL_SIZE * (FIELD_SIZE + 1), COLOR_MY);
    private final Field enemysField;

    private final Ship ship4_1, ship3_1, ship3_2, ship2_1, ship2_2, ship2_3, ship1_1, ship1_2, ship1_3, ship1_4;

    public BattleshipFrame() {
        setAlwaysOnTop(true);
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        setMinimumSize(new Dimension(1000, 720));
        setTitle("BattleShip Game");
        setResizable(false);
        getContentPane().setLayout(null);

        mainLabel = new YourLabel(0, 0, getWidth(), CELL_SIZE, "! text text text text text text text text !");

        {
            final Procedure_NoParam ref = this::refreshNumberOfShips;
            ship4_1 = new Ship(CELL_SIZE,      CELL_SIZE * 4, ref);
            ship3_1 = new Ship(CELL_SIZE * 6,  CELL_SIZE * 3, ref);
            ship3_2 = new Ship(CELL_SIZE * 6,  CELL_SIZE * 3, ref);
            ship2_1 = new Ship(CELL_SIZE * 10, CELL_SIZE * 2, ref);
            ship2_2 = new Ship(CELL_SIZE * 10, CELL_SIZE * 2, ref);
            ship2_3 = new Ship(CELL_SIZE * 10, CELL_SIZE * 2, ref);
            ship1_1 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref);
            ship1_2 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref);
            ship1_3 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref);
            ship1_4 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref);
        }

        enemysField = new Field(getWidth() - CELL_SIZE * (FIELD_SIZE + 1) - HALF_CELL_SIZE,
                CELL_SIZE,
                1 + CELL_SIZE * (FIELD_SIZE + 1),
                1 + CELL_SIZE * (FIELD_SIZE + 1),
                COLOR_ENEMY);

        addAllToContentPane(
                mainLabel, ship4Label, ship3Label, ship2Label, ship1Label,
                ship4_1, ship3_1, ship3_2, ship2_1, ship2_2, ship2_3, ship1_1, ship1_2, ship1_3, ship1_4,
                myField, enemysField);
    }

    public final void addAllToContentPane(Component... components) {
        Container contentPane = getContentPane();
        for (Component c : components) {
            contentPane.add(c);
        }
    }

    public void refreshNumberOfShips() {
        ship4Label.setNumberOfShips(countShipsOnPosition(ship4_1));
        ship3Label.setNumberOfShips(countShipsOnPosition(ship3_1, ship3_2));
        ship2Label.setNumberOfShips(countShipsOnPosition(ship2_1, ship2_2, ship2_3));
        ship1Label.setNumberOfShips(countShipsOnPosition(ship1_1, ship1_2, ship1_3, ship1_4));
    }

    private static int countShipsOnPosition(Ship... ships) {
        int numberOfShips = 0;
        for (Ship ship : ships) {
            if (ship.isOnPosition()) {
                numberOfShips++;
            }
        }
        return numberOfShips;
    }
}

Ship.java
Код: 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.
package battleship;

import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JTextField;

import static javax.swing.BorderFactory.createMatteBorder;
import static battleship.BattleshipFrame.CELL_SIZE;
import static battleship.BattleshipFrame.HALF_CELL_SIZE;
import static battleship.BattleshipFrame.SHIP_TOP_LINE_Y;
import static battleship.BattleshipFrame.THIRD_CELL_SIZE;

class Ship extends JTextField {

    private Point pointMouse;
    private final static Color
            COLOR_FILL   = new Color(204, 204, 255),
            COLOR_BORDER = new Color(51, 51, 51);

    public final int startX, startY;
    public int height, width;

    public Ship(int x, int y, int w, int h, final Procedure_NoParam refreshNumberOfShips) {

        //<editor-fold defaultstate="collapsed" desc="init">
        setEditable(false);
        setBackground(COLOR_FILL);
        setBorder(createMatteBorder(1, 1, 1, 1, COLOR_BORDER));
        setDragEnabled(true);

        addMouseListener(new MouseAdapter() {
            @Override public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    if (startX == getX() && startY == getY()) {
                        setBounds(getX(), getY(), getHeight(), getWidth());
                        int tmp = height;
                        height = width;
                        width = tmp;
                    }
                }
            }

            @Override public void mousePressed(MouseEvent e) {
                pointMouse = getMousePosition();
            }

            @Override public void mouseReleased(MouseEvent e) {
                refreshNumberOfShips.call();

                int x = getX() + e.getX() - pointMouse.x;
                int y = getY() + e.getY() - pointMouse.y;
                if (isPointOnField(x, y)) {
                    setLocation(getPointOnMyField(x, y));
                } else {
                    setLocation(startX, startY);
                }
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override public void mouseDragged(MouseEvent e) {
                setLocation(getPointOnMyField(getX() + e.getX() - pointMouse.x,
                                              getY() + e.getY() - pointMouse.y));
            }
        });
        //</editor-fold>

        startX = x;
        startY = y;
        height = h / CELL_SIZE;
        width = w / CELL_SIZE;
        setBounds(startX, startY, w, h);
    }

    public Ship(int x, int h, Procedure_NoParam refreshNumberOfShips) {
        this(x, SHIP_TOP_LINE_Y, CELL_SIZE, h, refreshNumberOfShips);
    }

    private boolean isPointOnField(int x, int y) {
        return CELL_SIZE - THIRD_CELL_SIZE <= x
                && CELL_SIZE * 2 - THIRD_CELL_SIZE <= y
                && CELL_SIZE * (11 - width) + THIRD_CELL_SIZE >= x
                && CELL_SIZE * (12 - height) + THIRD_CELL_SIZE >= y;
    }

    private Point getPointOnMyField(int x, int y) {
        Point point = new Point(x, y);
        if (isPointOnField(point.x, point.y)) {
            int modX = point.x % CELL_SIZE;
            if (modX > HALF_CELL_SIZE) {
                point.setLocation(point.x + CELL_SIZE - modX, point.y);
            } else {
                point.setLocation(point.x - modX, point.y);
            }

            int modY = point.y % CELL_SIZE;
            if (modY > HALF_CELL_SIZE) {
                point.setLocation(point.x, point.y + CELL_SIZE - modY);
            } else {
                point.setLocation(point.x, point.y - modY);
            }
        }
        return point;
    }

    public boolean isOnPosition() {
        return startX == getX() && startY == getY();
    }
}

Procedure_NoParam.java
Код: java
1.
2.
3.
4.
5.
package battleship;

public interface Procedure_NoParam {
    void call();
}

...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38728513
scf
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
На тему почитать:
http://www.ozon.ru/context/detail/id/2457392/

Главное, применять без фанатизма.
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38728583
Denyss
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
avp.mk, спасибо. Супер!
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38739473
Denyss
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
avp.mk, привет.

Проектирование классов 2:

BattleshipFrame.java
Код: 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.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
package BattleshipFrame;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

public class BattleshipFrame extends JFrame {
    public static final Color COLOR_MY = new Color(0, 204, 255),
            COLOR_ENEMY = new Color(35, 45, 55);

    public final static int CELL_SIZE = 40,
            HALF_CELL_SIZE = CELL_SIZE / 2,
            THIRD_CELL_SIZE = CELL_SIZE / 3,
            QUARTER_CELL_SIZE = CELL_SIZE / 4,
            FIELD_SIZE = 10,
            SHIP_TOP_LINE_Y = CELL_SIZE * (FIELD_SIZE + 2) + HALF_CELL_SIZE;

    private MyLabel mainLabel,
            ship4Label = new MyLabel(0, "1 pcs."),
            ship3Label = new MyLabel(CELL_SIZE * 5, "2 pcs."),
            ship2Label = new MyLabel(CELL_SIZE * 9, "3 pcs."),
            ship1Label = new MyLabel(CELL_SIZE * 12, "4 pcs.");

    private Location
            myLocation = new Location(),
            enemyLocation = new Location();
    
    private Field myField, enemyField;
    private Ship ship4_1, ship3_1, ship3_2, ship2_1, ship2_2, ship2_3, ship1_1, ship1_2, ship1_3, ship1_4;
    private Ship[] ships = {ship4_1, ship3_1, ship3_2, ship2_1, ship2_2, ship2_3, ship1_1, ship1_2, ship1_3, ship1_4};

    private MyJButton button;
            
    public BattleshipFrame() {
        initComponents();
        setVisible(true);
    }

    private void initComponents() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMinimumSize(new java.awt.Dimension(1000, 720));
        setTitle("BattleShip Game");
        setResizable(false);
        getContentPane().setLayout(null);

        mainLabel = new MyLabel(0, 0, getWidth(), CELL_SIZE, "Put up the ships on positions and press on START");

        {
            final Procedure_NoParam ref = new Procedure_NoParam() {
                public void call() {
                    BattleshipFrame.this.refreshNumberOfShips();
                }
            };
            final Procedure_FourParams ref2 = new Procedure_FourParams() {
                public boolean call(int x, int y, int height, int width) {
                    return BattleshipFrame.this.isPointOnShips(x, y, height, width);
                }
            };
            ship4_1 = new Ship(CELL_SIZE, CELL_SIZE * 4, ref, ref2);
            ship3_1 = new Ship(CELL_SIZE * 6, CELL_SIZE * 3, ref, ref2);
            ship3_2 = new Ship(CELL_SIZE * 6, CELL_SIZE * 3, ref, ref2);
            ship2_1 = new Ship(CELL_SIZE * 10, CELL_SIZE * 2, ref, ref2);
            ship2_2 = new Ship(CELL_SIZE * 10, CELL_SIZE * 2, ref, ref2);
            ship2_3 = new Ship(CELL_SIZE * 10, CELL_SIZE * 2, ref, ref2);
            ship1_1 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref, ref2);
            ship1_2 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref, ref2);
            ship1_3 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref, ref2);
            ship1_4 = new Ship(CELL_SIZE * 13, CELL_SIZE, ref, ref2);
        }

        myField = new Field(0,
                CELL_SIZE,
                1 + CELL_SIZE * (FIELD_SIZE + 1),
                1 + CELL_SIZE * (FIELD_SIZE + 1),
                COLOR_MY);

        enemyField = new Field(getWidth() - CELL_SIZE * (FIELD_SIZE + 1) - HALF_CELL_SIZE,
                CELL_SIZE,
                1 + CELL_SIZE * (FIELD_SIZE + 1),
                1 + CELL_SIZE * (FIELD_SIZE + 1),
                COLOR_ENEMY);

        {
            final Procedure_NoParam ref3 = new Procedure_NoParam() {
                public void call() {
                    try {
                        BattleshipFrame.this.start();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(BattleshipFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            button = new MyJButton("Start", getWidth() - 100, getHeight() - 90, 80, 40, ref3);
        }
        
        addAllToContentPane(button,
                mainLabel, ship4Label, ship3Label, ship2Label, ship1Label,
                ship4_1, ship3_1, ship3_2, ship2_1, ship2_2, ship2_3,
                ship1_1, ship1_2, ship1_3, ship1_4, myField, enemyField);
    }

    public final void addAllToContentPane(Component... components) {
        Container contentPane = getContentPane();
        for (Component c : components) {
            contentPane.add(c);
        }
    }

    public void refreshNumberOfShips() {
        ship4Label.setNumberOfShips(countNumberOfShips(ship4_1));
        ship3Label.setNumberOfShips(countNumberOfShips(ship3_1, ship3_2));
        ship2Label.setNumberOfShips(countNumberOfShips(ship2_1, ship2_2, ship2_3));
        ship1Label.setNumberOfShips(countNumberOfShips(ship1_1, ship1_2, ship1_3, ship1_4));
    }

    private int countNumberOfShips(Ship... ships) {
        int numberOfShips = 0;
        for (Ship ship : ships) {
            if (ship.isOnStartPosition()) {
                numberOfShips++;
            }
        }
        return numberOfShips;
    }
    
    public boolean isPointOnShips(int x, int y, int w, int h) {
        return countPointOnShips(x, y, w, h, ship4_1, ship3_1, ship3_2,
                ship2_1, ship2_2, ship2_3,
                ship1_1, ship1_2, ship1_3, ship1_4) > 1;
    }
    
    private int countPointOnShips(int pointX, int pointY, int height, int width, Ship... ships) {
        int PointOnShips = 0;
        for (Ship ship : ships) {
            if (ship.isPointOnMe(pointX, pointY, height, width)) {
                PointOnShips++;
            }
        }
        return PointOnShips;
    }
    
    public void start() throws InterruptedException {
        if (!ship4_1.isOnStartPosition() &&
            !ship3_1.isOnStartPosition() &&
            !ship3_2.isOnStartPosition() &&
            !ship2_1.isOnStartPosition() &&
            !ship2_2.isOnStartPosition() &&
            !ship2_3.isOnStartPosition() &&
            !ship1_1.isOnStartPosition() &&
            !ship1_2.isOnStartPosition() &&
            !ship1_3.isOnStartPosition() &&
            !ship1_4.isOnStartPosition()) {
            myLocation.generate(ship4_1, ship3_1, ship3_2,
                    ship2_1, ship2_2, ship2_3,
                    ship1_1, ship1_2, ship1_3, ship1_4);
            enemyLocation.generate();
            button.setVisible(false);
            button.repaint();
            //BattleshipCourse battle = new BattleshipCourse(myLocation, enemyLocation, myField, enemyField);
            enemyField.setReadyToShot();
            while (!myLocation.isKilled() && !enemyLocation.isKilled()) {                
                //enemyShot(enemyLocation, myField);
                Point shotPoint = new Point();
                shotPoint = getShotPoint(enemyField);
                //shot(myLocation, enemyField, shotPoint);
            }
        }
    }
    
    private Point getShotPoint(Field field) throws InterruptedException {
        Point shotPoint = new Point(-1, -1);
        do {
            shotPoint = field.getShotPoint();
        } while (shotPoint.x == -1 || shotPoint.y == -1);
        return shotPoint;
    }
}

Field.java
Код: 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.
package BattleshipFrame;

import static BattleshipFrame.BattleshipFrame.CELL_SIZE;
import static BattleshipFrame.BattleshipFrame.FIELD_SIZE;
import static BattleshipFrame.BattleshipFrame.HALF_CELL_SIZE;
import static BattleshipFrame.BattleshipFrame.QUARTER_CELL_SIZE;
import static BattleshipFrame.BattleshipFrame.THIRD_CELL_SIZE;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

public class Field extends JPanel{
    
    private final Font font = new Font("Tahoma", 0, 20);
    public final Color colorGrey = new Color(51, 51, 51);
    private final char[] topChars = {'A','B','C','D','E','F','G','H','I','K'};
    private final char[] leftChars = {'0','1','2','3','4','5','6','7','8','9'};
    private Color colorLine;
    private boolean isReadyToShot = false;
    private Point shotPoint = new Point(-1, -1);
    
    public Field () {}

    Field(int x, int y, int w, int h, Color color) {
        setBounds(x, y, w, h);
        colorLine = color;
        setBackground(new Color(1,1,1));
        
        addMouseListener(new MouseAdapter() {
            @Override public synchronized void mousePressed(MouseEvent e) {
                if (isReadyToShot) {
                    int x, y;
                    x = convertXY(e.getX());
                    y = convertXY(e.getY());
                    if (x >= 0 && x < FIELD_SIZE && y >= 0 && y < FIELD_SIZE) {
                        shotPoint.setLocation(x, y);
                        System.out.println("Shot: (" + shotPoint.x + ", " + shotPoint.y + ")");
                    }
                }
                notify();
            }
        });
    }
    
    @Override
    @SuppressWarnings("empty-statement")
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        
        g2.setColor(colorGrey);
        g2.setFont(font);
        for (int i = 0; i < FIELD_SIZE; i++) {
            g2.drawChars(topChars, i, 1,
                   CELL_SIZE * (i + 1) + THIRD_CELL_SIZE,
                   CELL_SIZE - QUARTER_CELL_SIZE);
        }

        for (int i = 0; i < FIELD_SIZE; i++) {
            g2.drawChars(leftChars, i, 1,
                  HALF_CELL_SIZE,
                  CELL_SIZE * (i + 2) - THIRD_CELL_SIZE);
        }
                
        g2.setColor(colorLine);
        for (int i = 1; i <= FIELD_SIZE; i++) {
            for (int j = 1; j <= FIELD_SIZE; j++) {
                g.drawRect(CELL_SIZE * i, CELL_SIZE * j,
                       CELL_SIZE, CELL_SIZE);
            }
        }
    }
    
    public void setReadyToShot() {
        isReadyToShot = true;
    }
    
    public synchronized Point getShotPoint() throws InterruptedException {
        wait(10000);
        Point tmpPoint = new Point(shotPoint.x, shotPoint.y);
        shotPoint.setLocation(-1, -1);
        return tmpPoint;
    }
    
    private int convertXY(int i) {
        return (i - CELL_SIZE) / CELL_SIZE;
    }
}



Проблема : Происходит зацикливание в getShotPoint, я ожидал, что во время wait(10000) в getShotPoint произойдет mousePressed и новое значение shotPoint будет установлено, но mousePressed не происходит. Хотя, до того как зайти в getShotPoint, mousePressed в field работает. Я использовал synchronized, но не помогло.

Что я делаю не так? И как лучше здесь поступить?
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38739827
smackmychi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Denyss,

Здесь, кажется, несколько пунктов - не так.

Например, ships.length - вернет вам количество элементов данного массива. Вместо нагромождения цикла в методе countNumberOfShips

Почитаю еще.
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38739850
smackmychi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Denyss,

Попробуйте синхронизироваться по объекту.

В классе Field опишите новое поле

Код: java
1.
private final Object lockObj = new Object();



Далее добавляете слушателя нажатия следующим образом (заменяете ваш способ)

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
        addMouseListener(new MouseAdapter() {
            @Override public void mousePressed(MouseEvent e) {
                if (isReadyToShot) {
                    int x, y;
                    x = convertXY(e.getX());
                    y = convertXY(e.getY());
                    if (x >= 0 && x < FIELD_SIZE && y >= 0 && y < FIELD_SIZE) {
                        shotPoint.setLocation(x, y);
                        System.out.println("Shot: (" + shotPoint.x + ", " + shotPoint.y + ")");
                    }
                }
                synchronized(lockObj){
                    notify();
                }
            }
        });



Замените вызов метода wait(10000) на
Код: java
1.
2.
3.
synchronized (lockObj) {
                lockObj.wait(10000);
            }
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38739856
smackmychi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
smackmychi,

Ошибочка.
В обработчике не просто notify(), а lockObj.notify()
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38740046
Denyss
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
smackmychi,

Добавил lockObj с синхронизацией на нем - не помогло, сделал синхронизацию по shotPoint - не помогло. Думаю, проблема в чем-то еще, смотри Battleship.rar. После нажатия кнопки "старт", уже никакой liseners не работают.

Где я налажал?
...
Рейтинг: 0 / 0
Помочь новичку в проектировании классов
    #38740083
smackmychi
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Denyss,

Чето там столько всего накручено и с потоками еще хрен знает для чего. Воу-воу-воу
...
Рейтинг: 0 / 0
12 сообщений из 12, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Помочь новичку в проектировании классов
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


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