【发布时间】:2017-06-02 16:44:55
【问题描述】:
我有一个小 Rect 的小游戏,它正在移动,我需要通过在我的 onUpdate 方法中执行 this.update(MyGraphics) 来更新 Graphics,该方法每 50 毫秒调用一次。但是当我这样做时this.update(MyGraphics) 我所有的buttons 和textfields 都会出现故障。
有人知道如何解决它吗?
【问题讨论】:
我有一个小 Rect 的小游戏,它正在移动,我需要通过在我的 onUpdate 方法中执行 this.update(MyGraphics) 来更新 Graphics,该方法每 50 毫秒调用一次。但是当我这样做时this.update(MyGraphics) 我所有的buttons 和textfields 都会出现故障。
有人知道如何解决它吗?
【问题讨论】:
当我这样做时 this.update(MyGraphics) 我所有的按钮和文本字段都会出现故障。
不要直接调用update(...)。这不是自定义绘画的方式。
当您进行自定义绘画时,您会覆盖 JPanel 的 paintComponent(...) 方法:
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// add your custom painting here
}
我有一个小 Rect 的小游戏,它在移动
如果你想要动画,那么你应该使用Swing Timer 来安排动画。然后当 Timer 触发时,您调用自定义类的方法来更改矩形的位置,然后调用 repaint()。这将导致面板被重新绘制。
阅读Swing Tutorial。有以下部分:
从基本示例开始。
【讨论】:
这是如何通过计时器更新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();
}
}
【讨论】:
paintComponent(...)。