简体   繁体   English

如何刷新JPanel?

[英]How do I refesh a JPanel?

I've been writing a program in java, so I decided to use Swing as my GUI. 我一直在用Java编写程序,所以我决定使用Swing作为我的GUI。 I don't have a lot of experience with swing, so I'm not sure as to how exactly it manages the objects I send to it. 我对Swing没有太多的经验,所以我不确定它如何精确地管理发送给它的对象。

My program contains a graph that needs to be updated regularly (maybe 10 times per second), drawn in a JPanel using the following code: 我的程序包含一个需要定期更新的图形(可能每秒更新10次),该图形使用以下代码在JPanel中绘制:

private JFrame graphWindow = new JFrame("Graph");
graph = new JPanel()
{
    protected void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        // Draw the graph and labels in g2

    }
}
graphWindow.add(graph, BorderLayout.CENTER);
graphWindow.pack();
graphWindow.setSize(windowDimensions);
graphWindow.setVisible(true);

Right now I have it so that the graph displays itself once, but I don't know how to tell it to refresh. 现在,我拥有了它,这样图形就可以显示一次,但是我不知道如何告诉它刷新。 I know how to write loops that run over time, but I have no clue about how I can refresh the graph in the loop. 我知道如何编写随时间推移运行的循环,但是我不知道如何在循环中刷新图。

I appreciate whatever help you can give me. 感谢您能给我的任何帮助。

Have you looked in the Javadocs? 您看过Javadocs吗?

From java.awt.Component.repaint() : java.awt.Component.repaint()

Repaints this component. 重新绘制该组件。

If this component is a lightweight component, this method causes a call to this component's paint method as soon as possible. 如果此组件是轻型组件,则此方法将导致尽快调用此组件的paint方法。 Otherwise, this method causes a call to this component's update method as soon as possible. 否则,此方法将导致尽快调用此组件的update方法。

Note: For more information on the paint mechanisms utilitized by AWT and Swing, including information on how to write the most efficient painting code, see Painting in AWT and Swing. 注意:有关AWT和Swing利用的绘制机制的更多信息,包括有关如何编写最有效的绘制代码的信息,请参阅AWT和Swing中的绘制。

Since: 以来:
JDK1.0 JDK1.0

This can be used with Swing timers to repaint/"refresh" your graph at a regular interval. 可以与Swing计时器一起使用,以定期重绘/“刷新”图形。

Example: 例:

import javax.swing.Timer;

/// ...

final JPanel graph = new JPanel() {
    protected void paintComponent(Graphics g) {
        // ... your painting code ...
    }
}
// The following Timer repeats 10 times per second (100 millisecond delay):
Timer timer = new Timer(100, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        graph.repaint();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM