java - 如何刷新 JPanel?

标签 java swing

我一直在用 java 编写一个程序,所以我决定使用 Swing 作为我的 GUI。我对 swing 没有太多经验,所以我不确定它如何准确地管理我发送给它的对象。

我的程序包含一个需要定期更新(可能每秒 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);

现在我有了它,以便图表自行显示一次,但我不知道如何告诉它刷新。我知道如何编写随时间运行的循环,但我不知道如何刷新循环中的图形。

我很感激您能给我的任何帮助。

最佳答案

您查看过 Javadocs 吗?

来自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. Otherwise, this method causes a call to this component's update method as soon as possible.

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.

Since:
    JDK1.0

这可以与 Swing 计时器一起使用,以定期重新绘制/“刷新”图表。

示例:

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();
    }
});

关于java - 如何刷新 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27790109/

相关文章:

java - 如何在 JFrame 上正确显示 PNG

java - 如何从异步值创建千分尺?

java - 如何打破无限循环

java - 无法让我的组合框和按钮工作。实现带有按钮的框时出现问题

java - 如何可视化 Swing 控件中的焦点?

java - 单击 j/ToggleButton 然后设置图标/图像

java - 在 Java 中将 JLabels 数组添加到单个面板?

java - 即使数据库中包含实体,为什么 'EntityManager.contains(..)' 也会返回 false?

java - 类无法实例化

Java 将日期格式从自定义日期更改为 MM dd yyyy