gpt4 book ai didi

java - 如何刷新 JPanel?

转载 作者:行者123 更新时间:2023-12-01 22:30:49 25 4
gpt4 key购买 nike

我一直在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com