JFrame(Swing)更新(图形)错误

时间:2017-06-02 16:44:56

标签: java graphics jframe

我有一个带有小Rect的小游戏,它正在移动,我需要在我的Graphics方法中执行this.update(MyGraphics)更新onUpdate,每50个问题调用一次。但是,当我执行此操作this.update(MyGraphics)时,我的所有buttonstextfields都会出现故障。

有人知道如何解决它吗?

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:0)

  

当我这样做时,this.update(MyGraphics)我的所有按钮和文本字段都出现了问题。

不要直接调用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. 如何使用摇摆计时器
  3. 开始使用基本示例。