[英]paintComponent does not get called everytime I want it to
I was trying to visualize sorting algorithms with Graphics2D and Swing (dont know if thats a good idea, im just doing it for fun) in a little project and came to a point where I would call the update method and thus the paintCompenent method everytime an element in the array changes its value. 我试图在一个小项目中可视化使用Graphics2D和Swing的排序算法(不知道那是否是个好主意,我只是为了好玩而已),到了这样的地步,我每次都会调用update方法,因此调用paintCompenent方法数组中的元素更改其值。
The problem is that the paintComponent method aparrently only gets called after the algorithm is finished. 问题在于,仅在算法完成之后才调用paintComponent方法。 Here is the code of the algorithm:
这是算法的代码:
private void sortBubble() {
int n = array.length;
do {
int newn = 1;
for (int i = 0; i < n - 1; i++) {
if (array[i] > array[i + 1]) {
int index = array[i];
array[i] = array[i + 1];
array[i + 1] = index;
System.out.println("SWITCHED");
this.setChanged();
this.notifyObservers();
newn = i + 1;
}
}
n = newn;
} while (n > 1);
}
The code of the update method: 更新方法的代码:
public void update(Observable o, Object arg) {
if(draw!=null) {
drawPanel.remove(draw);
}
draw = new Plotter(array.array,this.getWidth(),this.getHeight());
drawPanel.add(draw);
drawPanel.validate();
System.out.println("UPDATED");
}
And the code of the JPanel class: 和JPanel类的代码:
private void draw(Graphics g) {
g2d = (Graphics2D) g;
int i;
for(i=0;i<array.length;i++) {
g2d.draw(new Line2D.Double(i, height, i, height-array[i]));
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
System.out.println("PLOTTED");
}
Is there a way so the JPanel actually updates everytime a value changes? 有没有一种方法可以让JPanel每次值更改时实际上进行更新?
Swing is a single threaded framework, that means that any long running/blocking code will cause the program to "stall", preventing it from been able to update the UI or respond to the user input. Swing是一个单线程框架,这意味着任何长时间运行/阻止的代码都将导致程序“停顿”,从而阻止其更新UI或响应用户输入。
See Concurrency in Swing for more details. 有关更多详细信息,请参见Swing中的并发 。
There are several ways you might fix this, you could use a SwingWorker
or Swing Timer
, depending on your needs/abilities. 有几种解决方法,可以根据需要/功能使用
SwingWorker
或Swing Timer
。
See Worker Threads and SwingWorker and How to use Swing Timers for more details 有关更多详细信息,请参见工作线程和SwingWorker以及如何使用Swing计时器 。
Also have a look at java multiple graphics for an example of a visualised sorting implementation 还可以查看Java多个图形作为可视化排序实现的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.