tags:

views:

99

answers:

3

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.)

+2  A: 

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();
Adamski
How could I call the "render" method in the Event Dispatch Thread?
János Harsányi
You simply call repaint() (see the example code I added). However, you only really need to do this if you're doing animation; Otherwise you would typically update your UI based on an event firing (e.g. button click) in which case it normally isn't necessary to explicitly call repaint().
Adamski
A: 

have a look at javax.swing.Timer documentation

http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Timer.html

It has code right at the top to fire an event on fixed interval.

ring bearer
Is this "better" than a normal thread?
János Harsányi
Swing timer's task is performed in the event dispatch thread. This means that the task can safely manipulate components, but it also means that the task should execute quickly.If your task might take a while to execute, then consider using a SwingWorker instead of or in addition to the timer. See http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html - for instructions about using the SwingWorker class and information on using Swing components in multi-threaded programs.
ring bearer
+1  A: 

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.

camickr