XMotion处理JComponents

时间:2016-04-25 01:51:49

标签: java jpanel jcomponent

我遇到了麻烦。我想在我的JPanel上绘制一个rect,它添加到我的JFrame contentPane中。我希望x位于set pos但是移动-x并重新开始+ x开始。即如果我有一个800 x 400的JPanel,我希望rext接收这些参数,但是沿着xaxis(x-Velx)移动自身重新绘制为800并继续-x方向。我知道这不是足够的信息,我所触及的书都不是基于我想要做的,所以我缺乏适当的术语。

1 个答案:

答案 0 :(得分:1)

//这是一个很好的例子

公共类AnimatedBoat {

public static void main(String[] args) {
    new AnimatedBoat();
}

public AnimatedBoat() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            JFrame frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new AnimationPane());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

    });
}

public class AnimationPane extends JPanel {

    private BufferedImage boat;
    private int xPos = 0;
    private int direction = 1;

    public AnimationPane() {
        try {
            boat = ImageIO.read(new File("boat.png"));
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    xPos += direction;
                    // change directions off window width
                    if (xPos + boat.getWidth() > getWidth()) { 
                        xPos = getWidth() - boat.getWidth();
                        direction *= -1;
                    } else if (xPos < 0) {
                        xPos = 0;
                        direction *= -1;
                    }
                    repaint();
                }

            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return boat == null ? super.getPreferredSize() : new Dimension(boat.getWidth() * 4, boat.getHeight());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        int y = getHeight() - boat.getHeight();
        g.drawImage(boat, xPos, y, this);

    }

}

}