我正在做一个程序,它创建一个由 50 个数字组成的数组,然后在面板中将它们绘制为矩形,大小基于数字。单击面板时,将对数组进行排序并重新绘制面板以显示正在排序的数字的某种动画。这是单击面板之前和之后的样子:
这是我的代码:
public class AnimatedSelectionSortPanel extends javax.swing.JPanel {
int[] numbers = new int[50];
int min = 20;
int max = 100;
private void loadArray() {
int num;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = min + (int) Math.random() * ((max - min) + 1);
}
}
public static void selectionSort(int[] x) {
for (int i = 0; i < x.length - 1; i++) {
int minIndex = i; // Index of smallest remaining value.
for (int j = i + 1; j < x.length; j++) {
if (x[minIndex] > x[j]) {
minIndex = j; // Remember index of new minimum
}
}
if (minIndex != i) {
//... Exchange current element with smallest remaining.
int temp = x[i];
x[i] = x[minIndex];
x[minIndex] = temp;
}
}
}
private void drawPass(Graphics g) {
int xPos = 10;
int yPos = 120;
int rectWidth = 1;
for (int num : numbers) {
g.setColor(Color.black);
g.drawRect(xPos, yPos, rectWidth, num);
xPos += 11;
}
}
@Override
public void paintComponent (Graphics g) {
while (numbers.length == 0) {
loadArray();
}
drawPass(g);
}
private void sortPanelMouseClicked(java.awt.event.MouseEvent evt) {
selectionSort(numbers);
sortPanel.repaint();
}
我遇到的问题是,当我单击面板时,框架中没有任何内容被绘制。有人可以告诉我我在做什么有什么问题吗?
如果有帮助,这是来自 GUI 构建器的自动生成的代码:
private void initComponents() {
sortPanel = new javax.swing.JPanel();
sortPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
sortPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
sortPanelMouseClicked(evt);
}
});
javax.swing.GroupLayout sortPanelLayout = new javax.swing.GroupLayout(sortPanel);
sortPanel.setLayout(sortPanelLayout);
sortPanelLayout.setHorizontalGroup(
sortPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 398, Short.MAX_VALUE)
);
sortPanelLayout.setVerticalGroup(
sortPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 165, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sortPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(sortPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>