所以我想通过循环绘制几个矩形来表示JPanel上图形条形图中的值。
我已经扩展了JPanel以包含我的绘画命令,并且我有一个循环,它调用数组中的值并沿轴的点绘制它们。但是,当我运行我的程序时,它只绘制最后一个?
.repaint()
会重置我的画布吗?
它只是重新绘制我的缓冲图像,然后只在循环结束时更新我的面板吗?
我对JPanel的扩展:
class myJPanel extends JPanel
{
private Rectangle2D.Double rectangle;
/**
* Override paintComnponent method with our draw commands
*
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// Change the dimension and location of the rectangle
// obtained from the user interface.
rectangle = new Rectangle2D.Double(iX, iY, iWidth, iHeight);
// Set the drawing colour, then draw a filled rectangle
// on the graphics context of the BufferedImage object
g2dImg.setPaint(Color.black);
g2dImg.fill(rectangle);
// Transfer the image from the BufferedImage to the JPanel to make it visible.
g.drawImage(img, 0, 0, null);
}
// super.paintComponent clears off screen pixmap,
// since we're using double buffering by default.
protected void clear(Graphics g) {
super.paintComponent(g);
// Also clear the BufferedImage object by drawing a white coloured filled rectangle all over.
g2dImg.setPaint(Color.WHITE);
g2dImg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
}
}
这是我的面板代码:
final myJPanel jPanelDraw = new myJPanel();
jPanelDraw.setLayout(new GridBagLayout());
jPanelDraw.setBounds(248, 152, 604, 257);
jPanelDraw.setBackground(Color.white);
jPanelDraw.setEnabled(false);
jPanelDraw.setPreferredSize(new Dimension(281, 155));
jPanelDraw.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
frmUSnowboarding.getContentPane().add(jPanelDraw);
//Instantiate the BufferedImage object and give it the same width
// and height as that of the drawing area JPanel
img = new BufferedImage(jPanelDraw.getWidth(),
jPanelDraw.getHeight(),
BufferedImage.TYPE_INT_RGB);
//Get its graphics context.
g2dImg = (Graphics2D)img.getGraphics();
//Draw a filled white coloured rectangle on the entire area to clear it.
g2dImg.setPaint(Color.WHITE);
g2dImg.fill(new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight()));
这是我的循环,它位于我的绘图按钮的动作监听器中:
for (int iI = 0; iI < 6; iI++) {
iHeight = (double) iaRun1[iI];
iX = 0 + (iI * 40);
iY = (double) (jPanelDraw.getHeight() - iHeight);
jPanelDraw.repaint();
}
答案 0 :(得分:1)
并不是它只重画一次,它只是在循环结束后重新绘制。
repaint
方法不会立即重新绘制,而是标记要尽快重新绘制的面板(但现在不是)。
Swing不使用线程,所以一次只能运行。 Swing在幕后做了很多任务,在调用你的听众之间,其中一个任务是重新绘制需要重新绘制的窗口。在听众运行时,Swing不会重新绘制窗口。
此外,即使repaint
立即重绘,动画也会发生得太快,任何人都无法注意到。
答案 1 :(得分:0)
您可能在事件调度线程中运行该代码,在这种情况下,UI不会在循环之后重新绘制。如果您调试代码,您会发现jPanelDraw.repaint();
被多次调用,但UI的实际更新被放入被阻止的同一事件队列中通过你的循环。
尝试在SwingWorker
或Timer
中执行该循环。