В настоящее время я пытаюсь запрограммировать графический интерфейс для игры в реверси (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
Обновление Jlabel во время работы программы ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1738010692
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[i], ".");
}
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[i][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[i][j], "O")) {
count++;
}
}
}
return count;
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79391982/updating-a-jlabel-while-the-programs-running[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия