对于我的算法类,我们必须使用合并排序对数组进行排序,并在每一步将数组绘制为直方图,以图形方式查看发生了什么。我在使用paintComponent 方法更新数组时遇到了问题。当我第一次运行该程序时,它会显示混乱的数组(应该如此),然后当我单击合并排序按钮时,我希望看到排序后的数组,但我什么也没得到。任何帮助将不胜感激,谢谢。
注意:我知道我现在没有使用合并排序,我只是想让图形首先工作。
package a2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class GraphicalSort extends JFrame implements ActionListener {
static int[] data = new int[200];
JPanel panel = new JPanel(); //Panel to hold graphical display of array
JPanel buttonsPanel = new JPanel();
JButton mButton = new JButton("Mergesort");
int xPos = 0;
static int barWidth = 8;
static int barHeight = 1;
public GraphicalSort() {
setLayout(new BorderLayout());
mButton.addActionListener(this);
buttonsPanel.add(mButton);
for (int i = 0; i < data.length; i++) {
data[i] = (int) (500 * Math.random() + 1);
}
setSize(barWidth * data.length, barHeight * 500 + buttonsPanel.getHeight());
panel = new ArrayPanel();
add(buttonsPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
repaint();
validate();
}
public static void main(String[] args) {
GraphicalSort gs = new GraphicalSort();
gs.setTitle("Graphical Sort");
gs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gs.setLocationRelativeTo(null);
gs.setResizable(false);
gs.setVisible(true);
}
@SuppressWarnings("serial")
class ArrayPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
for (int i = 0; i < data.length; i++) {
g.fillRect(xPos, (barHeight * 500) - (barHeight * data[i]), barWidth, barHeight * data[i]);
xPos += barWidth;
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
remove(panel);
if (e.getSource() == mButton) {
Arrays.sort(data);
panel = new ArrayPanel();
}
add(panel, BorderLayout.CENTER);
repaint();
validate();
}
}