2017-06-02 31 views
0

我有一个小Rect的游戏,它正在移动,我需要通过在我的onUpdate方法中执行this.update(MyGraphics)来更新Graphics,该方法每50毫秒调用一次。但是,当我这样做this.update(MyGraphics)我所有的buttonstextfields都会出现问题。JFrame(Swing)更新(图形)错误

有人知道如何解决它吗?

回答

0

以下是如何通过定时器更新JPanel的示例之一。

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 

public class MainClass extends JPanel { 

    static JFrame frame = new JFrame("Oval Sample"); 
    static MainClass panel = new MainClass(Color.CYAN); 
    static Color colors[] = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW}; 
    static Color color; 
    static int step = 0; 

    public MainClass(Color color) { 
     this.color = color; 
    } 

    final static Timer tiempo = new Timer(500, new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
//   paintComponent(); 
      System.out.println("Step: " + step++); 
      if (step % 2 == 0) { 
       color = Color.DARK_GRAY; 
      } else { 
       color = Color.BLUE; 
      } 
      panel.repaint(); 
     } 
    }); 

    @Override 
    public void paintComponent(Graphics g) { 
     int width = getWidth(); 
     int height = getHeight(); 
     g.setColor(color); 
     g.drawOval(0, 0, width, height); 
    } 

    public static void main(String args[]) { 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new GridLayout(2, 2)); 
     panel = new MainClass(colors[2]); 
     frame.add(panel); 
     frame.setSize(300, 200); 
     frame.setVisible(true); 
     tiempo.start(); 
    } 
} 
+0

你应该重载'paintComponent(...)'。 – camickr

+0

这是行不通的,因为只有当我点击下一个圆形按钮时,Paint方法才会更新//我与Jpanel交互,但是我希望它在没有我做任何事情的情况下更新 –

+0

它没有解决我的问题,所以我会说不 –

0

当我做这个this.update(MyGraphics)我所有的按钮和文本框的glitched。

请勿直接调用update(...)。这不是定制绘画完成的方式。

相反,当你的风俗画,你重写JPanel的paintComponent(...)方法:

@Override 
protected void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 

    // add your custom painting here 
} 

我有一个小矩形,一个小游戏。如果你想要的动画被移动

那么你应该使用Swing Timer安排动画。然后,当Timer触发时,调用自定义类的方法来更改矩形的位置,然后调用repaint()。这将导致面板被重新粉刷。

阅读Swing Tutorial。上有几个部分:

  1. 表演风俗画
  2. 如何使用Swing计时器

让你的开始基本的例子。