Lab8

mail@pastecode.io avatar
unknown
java
10 months ago
2.4 kB
4
Indexable
Never
// Car Component
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;

    public class CarComponent extends JComponent {
        private int x;

        public CarComponent() {
            x = 0;
        }

        public void moveX(int movement) {
            x += movement;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            CarShape carShape = new CarShape(x, 0, 240, 120);
            carShape.draw(g2);
        }

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

// Car Shape
import java.awt.*;

public class CarShape {
    private int x, y, width, height;

    public CarShape(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public void draw(Graphics2D g2) {
        // Draw the body of the car as a rectangle
        g2.setColor(Color.RED);
        g2.fillRect(x, y, width, height / 2);

        // Draw the left tire as an oval
        g2.setColor(Color.BLACK);
        g2.fillOval(x + width / 8, y + height / 2, width / 8, height / 4);

        // Draw the right tire as an oval
        g2.fillOval(x + 6 * width / 8, y + height / 2, width / 8, height / 4);

        // Draw a blue rectangle on top of the two ovals
        g2.setColor(Color.BLUE);
        g2.fillRect(x + width / 4, y, width / 2, height / 2);
    }
}

// Car Main
import javax.swing.*;
import java.awt.event.ActionEvent;

public class CarMain {
    private JPanel panel;
    private CarComponent car;
    private JButton leftBtn;
    private JButton rightBtn;

    public static void main(String[] args) {
        JFrame frame = new JFrame("CarMain");
        frame.setContentPane(new CarMain().panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
    public void moveLeft(ActionEvent e){
        car.moveX(-10);
        car.repaint();
    }
    public void moveRight(ActionEvent e){
        car.moveX(+10);
        car.repaint();
    }

    public CarMain() {
        leftBtn.addActionListener(this::moveLeft);
        rightBtn.addActionListener(this::moveRight);
    }
}
Leave a Comment