重绘方法编译不正确

时间:2013-12-14 21:37:50

标签: java swing timer repaint timertask

我试图在计时器任务中使用重绘,但是eclipse告诉我方法是未定义的,我不知道为什么。我相信我有所有适当的进口。以下只是我的代码的一小部分。

import java.awt.Color;
import java.awt.Graphics;
import java.util.TimerTask;
import java.util.Timer;

import javax.swing.JPanel;

class task extends TimerTask
{
    public void run()
    {
        repaint();
    }   
}

1 个答案:

答案 0 :(得分:1)

你正在调用一个尚未在其所在的类中声明的方法,因此Java,而不是“Eclipse”正在抱怨,这是理所当然的。

如果您尝试使用计时器间歇性地重绘Swing GUI组件,那么

  • 使用Swing Timer,而不是java.util.Timer,因为后者不能正确处理Swing线程。
  • 在Swing组件上调用repaint(),而不是在你正在做的任何事情上。
  • 最重要的是,请阅读Java和Java Swing教程,因为它将解释所有这些以及更多内容。

例如,尝试直接运行,然后尝试用石头运行它。这几乎是迷幻的:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings("serial")
public class MyRepaint extends JPanel {

   private static final Color COLOR_1 = Color.RED;
   private static final Color COLOR_2 = Color.BLUE;
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final int DELAY = 25;
   private int x1 = 0;
   private int y1 = 0;

   private int x2 = 20;
   private int y2 = 20;
   Paint myPaint = new GradientPaint(x1, y1, COLOR_1, x2, y2, COLOR_2, true);

   public MyRepaint() {
      new Timer(DELAY, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            x1++;
            y1++;
            x2++;
            y2++;

            x1 %= PREF_W;
            y1 %= PREF_H;
            x2 %= PREF_W;
            y2 %= PREF_H;
            myPaint = new GradientPaint(x1, y1, COLOR_1, x2, y2, COLOR_2, true);

            // the repaint method call below works because it is calling it on
            // the current object of this class, which extends JPanel
            // and thus has a repaint() method.
            repaint();
         }
      }).start();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g2.setPaint(myPaint);
      g2.fillRect(0, 0, PREF_W, PREF_H);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private static void createAndShowGui() {
      MyRepaint mainPanel = new MyRepaint();

      JFrame frame = new JFrame("MyRepaint");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}