21xrx.com
2024-11-22 12:06:46 Friday
登录
文章检索 我的文章 写文章
Java程序员的职业发展之路:实战代码案例分析
2023-06-16 09:23:26 深夜i     --     --
Java编程 实战代码 Java

Java是当前互联网行业最流行的编程语言之一,它具有跨平台性、稳定性和高性能等优点,因此在软件开发领域中得到了广泛应用。对于想要从事Java编程的人来说,掌握Java编程技能不仅对于找工作有帮助,也可以提高他们的职业竞争力。那么学习Java能干几年呢?以下是一些实战代码案例分析,帮助Java程序员探索他们的职业发展之路。

1. Java Web开发

Java Web开发是Java程序员最常见的领域之一。在这个领域,你需要掌握Java基础知识、Web技术、数据库等多个方面。一个典型的Java Web开发案例是搭建一个在线商城网站。为了实现这个目标,你需要使用Spring框架、MyBatis技术、MySQL数据库等。以下是一个Java Web开发案例的实现代码:


@Controller

@RequestMapping("/product")

public class ProductController {

  @Autowired

  private ProductService productService;

  @GetMapping("/{id}")

  public ModelAndView getProduct(@PathVariable("id") Long id) {

    Product product = productService.getProductById(id);

    return new ModelAndView("product/productDetail", "product", product);

  }

  @PostMapping("/add")

  public String saveProduct(Product product, BindingResult result, HttpServletRequest request) {

    //校验表单数据

    if (result.hasErrors())

      return "product/editProduct";

    

    //保存商品

    productService.saveProduct(product);

    return "redirect:/product/list";

  }

  @PutMapping("/update/{id}")

  public String updateProduct(@PathVariable("id") Long id, Product product) {

    productService.updateProduct(id, product);

    return "redirect:/product/list";

  }

  @DeleteMapping("/delete/{id}")

  public String deleteProduct(@PathVariable("id") Long id) {

    productService.deleteProduct(id);

    return "redirect:/product/list";

  }

}

@Service

public class ProductServiceImpl implements ProductService {

  @Autowired

  private ProductDao productDao;

  @Override

  public Product getProductById(Long id) {

    return productDao.getProductById(id);

  }

  @Override

  public List getProductList() {

    return productDao.getProductList();

  }

  @Override

  public void saveProduct(Product product) {

    productDao.saveProduct(product);

  }

  @Override

  public void updateProduct(Long id, Product product) {

    productDao.updateProduct(id, product);

  }

  @Override

  public void deleteProduct(Long id) {

    productDao.deleteProduct(id);

  }

}

@Repository

public class ProductDaoImpl implements ProductDao {

  @Autowired

  private JdbcTemplate jdbcTemplate;

  @Override

  public Product getProductById(Long id) {

    String sql = "SELECT * FROM product WHERE id=?";

    return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Product.class));

  }

  @Override

  public List getProductList() {

    String sql = "SELECT * FROM product";

    return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));

  }

  @Override

  public void saveProduct(Product product) {

    String sql = "INSERT INTO product(name, price, description) VALUES (?, ?, ?)";

    jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getDescription());

  }

  @Override

  public void updateProduct(Long id, Product product) {

    String sql = "UPDATE product SET name=?, price=?, description=? WHERE id=?";

    jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getDescription(), id);

  }

  @Override

  public void deleteProduct(Long id) {

    String sql = "DELETE FROM product WHERE id=?";

    jdbcTemplate.update(sql, id);

  }

}

2. Java桌面应用开发

Java桌面应用开发是另一个广泛应用的领域。Java平台提供了一个名为Swing的GUI工具包,可用于开发跨平台的桌面应用程序。一个典型的Java桌面应用程序案例是开发一个音乐播放器。以下是一个Java桌面应用程序案例的实现代码:


public class MusicPlayer extends JFrame {

  public MusicPlayer() {

    initComponents();

  }

  private void initComponents() {

    //窗口设置

    setTitle("MusicPlayer");

    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    setLocationByPlatform(true);

    //播放列表

    DefaultListModel playlistModel = new DefaultListModel<>();

    playlistModel.addElement("song1.mp3");

    playlistModel.addElement("song2.mp3");

    JList playlist = new JList<>(playlistModel);

    //播放控制面板

    JPanel controlPanel = new JPanel(new FlowLayout());

    JButton playButton = new JButton("Play");

    JButton pauseButton = new JButton("Pause");

    JButton stopButton = new JButton("Stop");

    controlPanel.add(playButton);

    controlPanel.add(pauseButton);

    controlPanel.add(stopButton);

    //添加组件

    add(new JScrollPane(playlist), BorderLayout.CENTER);

    add(controlPanel, BorderLayout.SOUTH);

    //注册事件

    playButton.addActionListener(e -> {

      String fileName = playlist.getSelectedValue();

      //TODO: 播放音乐

    });

    pauseButton.addActionListener(e -> {

      //TODO: 暂停播放

    });

    stopButton.addActionListener(e -> {

      //TODO: 停止播放

    });

  }

  public static void main(String[] args) {

    MusicPlayer player = new MusicPlayer();

    player.pack();

    player.setVisible(true);

  }

}

3. Java游戏开发

Java游戏开发是相对较少的领域,但它仍然有着比较有趣的项目。Java游戏通常被用于开发小型游戏,因为Java语言在性能方面的表现并不像C++那么优秀。一个典型的Java游戏案例是开发一个俄罗斯方块游戏。以下是一个Java游戏案例的实现代码:


public class TetrisGame extends JFrame {

  public TetrisGame() {

    super("Tetris Game");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setSize(220, 440);

    setResizable(false);

    setLocationRelativeTo(null);

    add(new TetrisBoard());

    setVisible(true);

  }

  public static void main(String[] args) {

    new TetrisGame();

  }

}

class TetrisBoard extends JPanel implements ActionListener {

  private final int size = 30;

  private final int boardWidth = 10;

  private final int boardHeight = 22;

  private final Timer timer;

  private boolean isGameOver;

  private Tetromino falling;

  private final ArrayList landed;

  private static final Color[] COLORS = {

      Color.BLACK, Color.CYAN, Color.blue, Color.orange, Color.yellow, Color.green, Color.pink, Color.red};

  private static final int[][][] SHAPES = {

      {{0, 0}, {0, 0}, {0, 0}, {0, 0}},

      {{0, -1}, {0, 0}, {-1, 0}, {-1, 1}}, //S

      {{0, -1}, {0, 0}, {1, 0}, {1, 1}}, //Z

      {{0, -1}, {0, 0}, {0, 1}, {0, 2}}, //I

      {{-1, 0}, {0, 0}, {1, 0}, {0, 1}}, //T

      {{0, 0}, {1, 0}, {0, 1}, {1, 1}}, //O

      {{-1, -1}, {0, -1}, {0, 0}, {1, 0}}, //J

      {{1, -1}, {0, -1}, {0, 0}, {-1, 0}} //L

  };

  public TetrisBoard() {

    super();

    setBackground(Color.white);

    landed = new ArrayList<>();

    falling = new Tetromino();

    timer = new Timer(400, this);

    timer.start();

    addKeyListener(new MyAdapter());

    setFocusable(true);

  }

  private boolean checkCollision() {

    for (Block b : falling.blocks) {

      if (b.row < 0 || b.row >= boardHeight || b.col < 0 || b.col >= boardWidth) {

        return true;

      }

      for (Tetromino t : landed) {

        if (t.blocks.contains(b)) {

          return true;

        }

      }

    }

    return false;

  }

  private void checkLanded() {

    if (checkCollision()) {

      if (falling.row == 0) {

        isGameOver = true;

        timer.stop();

      } else {

        landed.add(falling);

        falling = new Tetromino();

      }

    }

  }

  private void drawBlock(Graphics g, int row, int col, Color color) {

    g.setColor(color.lightGray);

    g.fillRect(col * size, row * size, size, size);

    g.setColor(color);

    g.fillRect(col * size + 1, row * size + 1, size - 2, size - 2);

  }

  private void drawLand(Graphics g) {

    for (Tetromino t : landed) {

      for (Block b : t.blocks) {

        drawBlock(g, b.row, b.col, COLORS[t.color]);

      }

    }

  }

  private void drawFalling(Graphics g) {

    for (Block b : falling.blocks) {

      drawBlock(g, b.row, b.col, COLORS[falling.color]);

    }

  }

  private void drawGameOver(Graphics g) {

    g.setColor(Color.red);

    g.drawString("Game Over", 60, boardHeight * size / 2);

  }

  @Override

  public void actionPerformed(ActionEvent e) {

    if (!isGameOver) {

      falling.moveDown();

      checkLanded();

    }

    repaint();

  }

  @Override

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    drawLand(g);

    drawFalling(g);

    if (isGameOver) {

      drawGameOver(g);

    }

  }

  private class MyAdapter extends KeyAdapter {

    @Override

    public void keyPressed(KeyEvent e) {

      int keycode = e.getKeyCode();

      switch (keycode) {

        case KeyEvent.VK_LEFT:

          falling.moveLeft();

          break;

        case KeyEvent.VK_RIGHT:

          falling.moveRight();

          break;

        case KeyEvent.VK_UP:

          falling.rotate();

          break;

        case KeyEvent.VK_DOWN:

          falling.moveDown();

          checkLanded();

          break;

      }

      repaint();

    }

  }

  private class Tetromino {

    private final ArrayList blocks;

    private int row;

    private int col;

    private int color;

    public Tetromino() {

      blocks = new ArrayList<>();

      row = 0;

      col = boardWidth / 2;

      color = (int) (Math.random() * 7) + 1;

      int type = color % 7;

      for (int i = 0; i < 4; i++) {

        blocks.add(new Block(row + SHAPES[type][i][0], col + SHAPES[type][i][1]));

      }

    }

    public void moveLeft() {

      for (Block b : blocks) {

        b.col--;

      }

      if (checkCollision()) {

        moveRight();

      }

    }

    public void moveRight() {

      for (Block b : blocks) {

        b.col++;

      }

      if (checkCollision()) {

        moveLeft();

      }

    }

    public void moveDown() {

      for (Block b : blocks) {

        b.row++;

      }

    }

    public void rotate() {

      if (color == 2) {  //Z

        return;

      }

      int type = color % 7;

      int[][] temp = new int[4][2];

      for (int i = 0; i < 4; i++) {

        temp[i][0] = SHAPES[type][i][1];

        temp[i][1] = -SHAPES[type][i][0];

      }

      for (int i = 0; i < 4; i++) {

        blocks.get(i).row = row + temp[i][1];

        blocks.get(i).col = col + temp[i][0];

      }

      if (checkCollision()) {

        for (Block b : blocks) {

          b.row -= temp[b.index][1];

          b.col -= temp[b.index][0];

        }

      }

    }

  }

  private static class Block {

    int row;

    int col;

    final int index;

    public Block(int r, int c) {

      row = r;

      col = c;

      index = TetrominoManager.getIndex();

    }

    @Override

    public boolean equals(Object obj) {

      if (this == obj) {

        return true;

      }

      if (obj == null || getClass() != obj.getClass()) {

        return false;

      }

      Block block = (Block) obj;

      return index == block.index;

    }

    @Override

    public int hashCode() {

      return Objects.hash(index);

    }

  }

  private static class TetrominoManager {

    private static int index;

    public static int getIndex() {

      index++;

      return index - 1;

    }

  }

}

Web开发,Java桌面应用开发,Java游戏开发。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复