无法使用计时器重新绘制窗口

时间:2013-01-18 20:53:00

标签: java

我有一个具有初始起始位置的按钮。按钮的Y轴始终保持不变,但x轴每秒都会改变。计时器每秒递增x的值10,并重新绘制窗口。 x的值似乎增加得很好但是即使调用了repaint和validate方法,组件也不会更新。

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.Timer;

public class TedmadLogo {

   JWindow myWindow = new JWindow();

   Container container = myWindow.getContentPane();

   JPanel panel = new JPanel();
   ImageIcon image = new ImageIcon("bg.jpg");
   ImageIcon image2 = new ImageIcon("bg2.jpg");
   JButton button1 = new JButton("Button");
   JLabel bg = new JLabel(image);
   JLabel bg2 = new JLabel(image2);
   int x = 50;

   ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
         x += 10;
         myWindow.getContentPane().validate();
         myWindow.getContentPane().repaint();
         System.out.println(x);
         timer.restart();
      }
   };

   Timer timer = new Timer(1000, taskPerformer);

   public TedmadLogo() {

      myWindow.setLayout(null);
      panel.setLayout(null);
      myWindow.setSize(600, 300);

      myWindow.setVisible(true);
      myWindow.setLocationRelativeTo(null);

      container.add(panel);
      panel.setBounds(0, 0, 600, 300);

      panel.add(button1);
      panel.add(bg2);
      panel.add(bg);
      button1.setBounds(x, 150, 30, 30);
      bg2.setBounds(150, 0, 600, 300);
      bg.setBounds(-150, 0, 600, 300);
   }

   public static void main(String[] args) {
      TedmadLogo logo = new TedmadLogo();
      logo.timer.start();
   }
}

0 个答案:

没有答案