Reputation: 6797
The JMenuItems
of JMenuBar
drops down to a JPanel
added to the JFrame, but the JPanel erases the JMenuItems
.
Do I supposed to pause the re-drawing of the JPanel?
I'm using getGraphics()
on the JPanel
for drawing an image, this method is called from a thread with (for example) 200 ms delay.
edit:
It's a (very simple) game inside the JPanel
.
(I've added a field paused
to the JPanel and i've edited the paint method so it repaints the JPanel
only if paused
is false
, however I don't know if this "solution" is good. (It's set to true
when the user clicks on the menu and set to false
when selects or cancels it.)
Upvotes: 0
Views: 552
Reputation: 20773
Have a look at javax.swing.Timer
documentation
https://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/Timer.html
It has code right at the top to fire an event on fixed interval.
Upvotes: 0
Reputation: 54697
You should always be repainting the JPanel
from the Event Dispatch Thread, not an arbitrary thread. If you want to do this in order to animate the panel (e.g. with the 200ms delay you mention) then consider using javax.swing.Timer
, which periodically fires an ActionEvent on the Event Dispatch Thread.
Example
public class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Add additional graphics operations here.
}
}
final JPanel panel = new MyPanel();
int delay = 200; // Milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.repaint();
}
};
new Timer(delay, taskPerformer).start();
Upvotes: 2
Reputation: 324098
I'm using getGraphics() on the JPanel for drawing an image
Never use the getGraphics() method like that. You have no control over when the component should be repainted. Custom painting should be done by overriding the paintComponent() method of the panel. When you use the Timer you just use panel.repaint() and the Swing repaint manager should look after the details of what needs to be painted.
Upvotes: 1