在JScrollPane中使用JPanel滚动动态生成的图形时,滚动的部分图形消失

时间:2016-04-12 06:06:23

标签: java swing jpanel jscrollpane

outputImage

一切正常但是当我在生成图形时滚动时,滚动的部分图形会消失

MainApp.java

JPanel

Canvas扩展paintComponent()。在这里,我将覆盖SwingWorker并调用draw方法来触发public class Canvas extends JPanel { ArrayList<CAGeneration> cAGenList; private int y,x; private Thread t; public static SwingWorker<Void, Void> worker; private int count = 0; private boolean check = false; public CACanvas(ArrayList<CAGeneration> cAGenList) { this.cAGenList = cAGenList; } @Override public Dimension getPreferredSize() { return new Dimension(800, 800); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); revalidate(); if(!check){ drawCA(g, this.cAGenList); } } private void drawCA(Graphics g, ArrayList<CAGeneration> cAGenList ) { worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { Graphics2D g2d = (Graphics2D) g; check = true; y= 10; count = 0; synchronized (cAGenList) { for(CAGeneration cg: cAGenList){ count++; y = y+10; x = 0; if(!isCancelled()){ System.out.println(Thread.currentThread().getName()); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } for(int i=0; i<cg.getcACell().length; i++){ x = x+10; if (cg.getcACell()[i] == 0) { paintRect(g2d, x, y, 9, Color.WHITE); } if (cg.getcACell()[i] == 1) { paintRect(g2d, x, y, 9, Color.GRAY); } if (cg.getcACell()[i] == 2) { paintRect(g2d, x, y, 9, Color.BLACK); } } } } } check = false; return null; } }; ExecutorService threadPool = Executors.newSingleThreadExecutor(); threadPool.submit(worker); } private void paintRect(Graphics2D g2D, int x, int y, int size, Color color){ if(g2D!=null) g2D = (Graphics2D) getGraphics(); g2D.setColor(color); g2D.fillRect(x, y, size, size); } } 绘制图形。

Canvas.java

{{1}}

0 个答案:

没有答案