Обновление Jlabel во время работы программыJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Обновление Jlabel во время работы программы

Сообщение Anonymous »

В настоящее время я пытаюсь запрограммировать графический интерфейс для игры в реверси (https://en.wikipedia.org/wiki/reversi), используя Java Swing. Часть моей задачи - распечатать текущее количество плиток игрока (синий) и машин (красная) в нижней части моей конфигурации моей кадры в начале. < /P>
Я создал jlabel для Каждый тип плиток и добавлял их в свою собственную jPanel. Однако, когда я пытаюсь обновить этикетки, вся панель начинает либо воспроизводить себя бесконечно повторяет всю плату с каждым поворотом, либо вообще не меняет метку. Я пытался написать коммерческую команду в каждом возможном месте, и все еще ничего не работает. Что я делаю не так? Где мне обновить метки? < /P>
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Objects;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

public class example {
JPanel panel = new JPanel();
private final int width = 60;
private final int diameter = (int) Math.round(width * 0.85);
private final int padding = (int) Math.round(width * 0.05);
private String[][] board;
private int SIZE = 8;

public example() {
board = newBoard();
JFrame frame = new JFrame();
frame.setTitle("Reversi");
frame.setLocationRelativeTo(null);
frame.setLocation(450, 150);
frame.setBackground(Color.BLACK);
frame.setPreferredSize(new Dimension(width * 8, width * 9));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new Shell());

JPanel bottom = new JPanel();

//Label for a number of player's tiles
JLabel humanPoints = new JLabel();
humanPoints.setText(String.valueOf(getNumberOfHumanTiles()));
humanPoints.setForeground(Color.BLUE);
humanPoints.setFont(new Font("Verdana", Font.BOLD, 20));
bottom.add(humanPoints);

//Just a test button, that creates a random combination of tiles
//To test, if the labels update correctly.
JButton testButton = new JButton("Test");
testButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
board = newBoard();
for (int i = 0; i < (int)(Math.random() * SIZE); i++) {
board[(int)(Math.random() * SIZE)][(int)(Math.random() * SIZE)] = "X";
}
for (int i = 0; i < (int)(Math.random() * SIZE); i++) {
board[(int)(Math.random() * SIZE)][(int)(Math.random() * SIZE)] = "O";
}
panel.repaint();
}
});
bottom.add(testButton);

//Label for a number of machine's tiles
JLabel machinePoints = new JLabel();
machinePoints.setText(String.valueOf(getNumberOfMachineTiles()));
machinePoints.setForeground(Color.RED);
machinePoints.setFont(new Font("Verdana", Font.BOLD, 20));
bottom.add(machinePoints);

frame.add(bottom, BorderLayout.SOUTH);

//A panel for a board 8x8.
panel = new JPanel(new GridLayout(SIZE, SIZE)) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

//Prints the tiles, according to the value of each tile
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
int row = i;
int col = j;
JPanel tile = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, width, width);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width, width);
switch (board[row][col]) {
case "X":
g.setColor(Color.BLUE);
g.fillOval(padding, padding, diameter, diameter);
g.setColor(Color.BLACK);
g.drawOval(padding, padding, diameter, diameter);
break;
case "O":
g.setColor(Color.RED);
g.fillOval(padding, padding, diameter, diameter);
g.setColor(Color.BLACK);
g.drawOval(padding, padding, diameter, diameter);
break;
default:
break;
}
}
};
panel.add(tile);
}
}
//If you write it here, it goes crazy and breaks the whole structure of a board
//But prints a correct number of tiles
//humanPoints.setText(String.valueOf(getNumberOfHumanTiles()));
//machinePoints.setText(String.valueOf(getNumberOfMachineTiles()));
}
};
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}

//Creates a start configuration of a board
private String[][] newBoard() {
String[][] newBoard = new String[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
Arrays.fill(newBoard, ".");
}

newBoard[SIZE / 2 - 1][SIZE / 2 - 1] = "X";
newBoard[SIZE / 2][SIZE / 2] = "X";
newBoard[SIZE / 2 - 1][SIZE / 2] = "O";
newBoard[SIZE / 2][SIZE / 2 - 1] = "O";
return newBoard;
}

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

public int getNumberOfHumanTiles() {
int count = 0;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (Objects.equals(board[j], "X")) {
count++;
}
}
}
return count;
}

public int getNumberOfMachineTiles() {
int count = 0;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (Objects.equals(board[j], "O")) {
count++;
}
}
}
return count;
}

}


Подробнее здесь: https://stackoverflow.com/questions/793 ... ms-running
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»