Приложение с интерфейсом JavaJAVA

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

Сообщение Anonymous »

Мне нужно создать приложение, которое управляет очередью в почтовом отделении только с одним входом и 4 доступными стойками.
Я не понимаю, почему, когда я добавляю нового клиента, оно ставит в очередь значки, но вместо того, чтобы удалять их по одному, он удаляет их все.

Код: Выделить всё

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.LinkedList;
import java.util.Queue;

public class MyFrame extends JFrame {
private static final int NUM_DESKS = 4;
private final JLabel[] deskLabels = new JLabel[NUM_DESKS];
private final Queue customerQueue = new LinkedList();
private int customerNumber = 1;
private final int serviceTime = 3000;

public MyFrame() {
super("Post Office Simulator");
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
initializeUI();
}

private void initializeUI() {
JPanel mainPanel = new JPanel(new BorderLayout());
add(mainPanel);
mainPanel.add(createDesksPanel(), BorderLayout.NORTH);
mainPanel.add(createQueuePanel(), BorderLayout.CENTER);
mainPanel.add(createAddCustomerButton(), BorderLayout.SOUTH);
}

private JPanel createDesksPanel() {
JPanel desksPanel = new JPanel(new GridLayout(1, NUM_DESKS, 10, 5));
desksPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
for (int i = 0; i < NUM_DESKS; i++) {
deskLabels[i] = new JLabel("Free", SwingConstants.CENTER);
deskLabels[i].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
deskLabels[i].setFont(new Font("Arial", Font.BOLD, 20));

desksPanel.add(deskLabels[i]);
}
desksPanel.setBackground(Color.WHITE);
return desksPanel;
}

private JPanel createQueuePanel() {
JPanel queuePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
queuePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20), "Customers Waiting", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Arial", Font.BOLD, 24), Color.BLUE));
queuePanel.setBackground(Color.WHITE);
return queuePanel;
}

private JButton createAddCustomerButton() {
JButton addCustomerButton = new JButton("Add Customer");
addCustomerButton.setFont(new Font("Arial", Font.BOLD, 20));
addCustomerButton.setHorizontalTextPosition(SwingConstants.LEADING);
addCustomerButton.setForeground(Color.WHITE);
addCustomerButton.setBackground(Color.GREEN.darker());
addCustomerButton.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
addCustomerButton.addActionListener(this::addCustomer);
return addCustomerButton;
}

private void addCustomer(ActionEvent e) {
// Name of the customer's icon file
String iconName = "man.png";

// Load the icon to represent the customer
ImageIcon customerIcon = new ImageIcon(getClass().getResource(iconName));

// Resize the icon
Image image = customerIcon.getImage();
Image scaledImage = image.getScaledInstance(50, 50, Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(scaledImage);

// Add the customer's ID to the queue
customerQueue.offer(iconName);

// Update the queue display
updateQueueDisplay(scaledIcon);

// Serve the next customer
serveNextCustomer();
}

private void serveNextCustomer() {
for (int i = 0; i < NUM_DESKS; i++) {
if (deskLabels[i].getText().equals("Free") && !customerQueue.isEmpty()) {
String customerId = customerQueue.poll();
deskLabels[i].setText(customerId);
simulateServiceTime(i);
updateQueueDisplay(new ImageIcon(getClass().getResource(customerId))); // Correction here
return;
}
}
}

private void simulateServiceTime(final int deskIndex) {
new Thread(() -> {
try {
Thread.sleep(serviceTime);  // Simulate service time
deskLabels[deskIndex].setText("Free");
serveNextCustomer(); // Check if there are more customers to serve
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}

private void updateQueueDisplay(ImageIcon customerIcon) {
JPanel queuePanel = (JPanel) ((JPanel) getContentPane().getComponent(0)).getComponent(1);

// Remove only the JLabels that have an icon
for (Component component : queuePanel.getComponents()) {
if (component instanceof JLabel) {
JLabel customerLabel = (JLabel) component;
if (customerLabel.getIcon() != null) {
queuePanel.remove(customerLabel);
}
}
}

// Add a JLabel for each customer in the queue
for (String customerId : customerQueue) {
JLabel customerLabel = new JLabel(customerId);
customerLabel.setIcon(customerIcon); // Set the icon for the customer
customerLabel.setPreferredSize(new Dimension(50, 50)); // Set preferred dimensions for the icon
queuePanel.add(customerLabel);
}

// Update the layout of the queue panel
queuePanel.revalidate();
queuePanel.repaint();
}
}

Я пытался найти решения в Интернете, но безуспешно

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

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

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

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

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

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