Reputation: 398
I've been writing a program in java, so I decided to use Swing as my 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.
My program contains a graph that needs to be updated regularly (maybe 10 times per second), drawn in a JPanel using the following code:
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.
Upvotes: 0
Views: 63
Reputation:
Have you looked in the Javadocs?
From 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
This can be used with Swing timers to repaint/"refresh" your graph at a regular interval.
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();
}
});
Upvotes: 3