簡體   English   中英

當單擊鼠標時,應在main方法的哪里放置新的mouseListener來向CarShape左右動畫?

[英]Where should I place a new mouseListener in the main method to animate CarShape left or right when the mouse is clicked?

下面是我的代碼。 我是java.swing和java.awt的新手。 我是否需要放入新的動作偵聽器以及mouseListener? 因為形狀在移動,所以我不確定如何設置此代碼。

public class Animation {

    private static boolean goingRight = true;
    private static int posRight;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        final MoveableShape shape = new CarShape(0, 0, CAR_WIDTH);
        ShapeIcon icon = new ShapeIcon(shape, ICON_WIDTH, ICON_HEIGHT);
        final JLabel label = new JLabel(icon);
        frame.setLayout(new FlowLayout());
        frame.add(label);
        frame.pack();
        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                if (posRight <= 0) {
                    goingRight = true;
                }
                if (posRight >= 300) {
                    goingRight = false;
                }
                if (goingRight) {
                    shape.translate(1, 0);
                    label.repaint();
                    posRight += 1;
                } else {
                    shape.translate(-1, 0);
                    label.repaint();
                    posRight -= 1;
                }

            }
        };
        final int DELAY = 100;
        Timer time = new Timer(DELAY, taskPerformer);
        time.start();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    private static final int ICON_WIDTH = 400;
    private static final int ICON_HEIGHT = 100;
    private static final int CAR_WIDTH = 100;
}

您可以包括MoveableShape和ShapeIcon的代碼嗎? 這樣可以更輕松地運行代碼並查看其功能。

如果要在單擊汽車時更改其方向,可以在包含汽車形狀圖標的標簽上添加一個鼠標偵聽器:

    label.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(final MouseEvent e) {
            // Change the direction here...
        }
    });

現在,只要您單擊標簽(汽車周圍的矩形),汽車就應該改變方向。

(在上面的示例中,我使用了MouseAdapter,它僅允許您實現所需的MouseListener接口的方法,其他方法則無濟於事。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM