开发者

JMenuBar dropping down to a "custom" JPanel and "erased"

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 (开发者_如何学JAVAvery 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.)


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜