慢慢画一条线

时间:2014-01-29 03:36:29

标签: java swing user-interface timer

我希望这能慢慢创建一条从10,0到10,600的画线。这条线甚至根本不会画,我觉得它不起作用的唯一原因是我的格式和放置不同的组件有点不对?为什么呢?

public class Moving extends JPanel {
    int counter;
    Timer time;
    public void setUp() {
        ActionListener action = new ActionListener() {  
            public void actionPerformed(ActionEvent event){
                counter++;
                repaint();

            }
        };
        time = new Timer(100, action);
        time.start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.drawRect(10, counter, 20, 20);
    } 


    public static void main(String[] args) {
        Moving game = new Moving();
                    JFrame frame = new JFrame("Frame"); 
        frame.setSize(320, 340);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
                    frame.add(game);
        game.setUp();
    }
}

1 个答案:

答案 0 :(得分:3)

您尚未将Moving添加到您创建的框架中...

<强>更新

我稍微更新了代码以演示这一点,将Moving添加到框架中。我还包括Initial Thread要求

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Moving extends JPanel {

    int counter;
    Timer time;

    public Moving() {
        ActionListener action = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                counter++;
                repaint();

            }
        };
        time = new Timer(100, action);
    }

    public void start() {
        time.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.drawRect(10, counter, 20, 20);
    }

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

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                Moving moving = new Moving();
                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(moving);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                moving.start();
            }
        });
    }
}