我一直无法让我的计时器显示我的条形图随着时间的推移自我更新,我所拥有的是我的图表自动排序,即使我将计时器设置为每隔几秒更新一次。
这是我的绘画和updatetextfieldthread
方法。
private class Display extends JPanel {
private Color color = Color.RED;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
Dimension d = getPreferredSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / array.length;
int x=0, y=0;
int base=410;
for(int i=0;i<array.length;i++){
x+=30;
y+=30;
int linethickness=20;
int linelength=50;
g.setColor(Color.red);
g.fillRect(x, base-linelength*array[i], linethickness , linelength*array[i]);
g.setColor(Color.black);
g.drawRect(x, base-linelength*array[i], linethickness, linelength*array[i]);
}
}
}
private class UpdateTextFieldThread extends SwingWorker<Void, Integer>
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
insertionSort(array);
display.repaint();
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
return null;
}
protected void process(java.util.List<Integer> list)
{
textfield.setText("" + list.get(list.size() - 1));
}
}
现在修改:我正在逐步分解我的排序方法,我正在更新它内部的线程,但它仍然没有打破我的图形。
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if (src == button1){
int[] array2=array;
for (int i = 1; i < array2.length; i++) {
int thingToInsert = array2[i];
int j = i - 1;
while (j >= 0 && thingToInsert<array2[j]) {
array2[j+1] = array2[j];
j--;
}
array2[j+1] = thingToInsert;
(new UpdateTextFieldThread()).execute();
}
}
}
}
private class UpdateTextFieldThread extends SwingWorker<Void, Integer>
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
ExecutorService service = Executors.newSingleThreadExecuto();
try {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(THREAD_DELAY);
display.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
return null;
}