chess board in java

前端 未结 6 2086
夕颜
夕颜 2020-12-09 06:56

This is my code below

import javax.swing.*;
import java.awt.*;

public class board2 {

JFrame frame;
JPanel squares[][] = new JPanel[8][8];

public board2()          


        
6条回答
  •  悲&欢浪女
    2020-12-09 07:46

    public class Pieces {
    
    }
    
    class Pawn_1 extends JComponent {
    
            private BufferedImage img;
            private Point imgPoint = new Point(0, 65);
    
            public Pawn_1() {
                try {
                    img = ImageIO.read(new File("C:\\imgs\\b_pawn.png"));
    
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
    
                MouseAdapter ma = new MouseAdapter() {
    
                    private Point offset;
    
                    @Override
                    public void mousePressed(MouseEvent e) {
                        Rectangle bounds = getImageBounds();
                        Point mp = e.getPoint();
                        if (bounds.contains(mp)) {
                            offset = new Point();
                            offset.x = mp.x - bounds.x;
                            offset.y = mp.y - bounds.y;
                        }
                    }
    
                    @Override
                    public void mouseReleased(MouseEvent e) {
                        offset = null;
                    }
    
                    @Override
                    public void mouseDragged(MouseEvent e) {
                        if (offset != null) {
                            Point mp = e.getPoint();
                            imgPoint.x = mp.x - offset.x;
                            imgPoint.y = mp.y - offset.y;
                            repaint();
                        }
                    }
    
                };
                addMouseListener(ma);
                addMouseMotionListener(ma);
            }
    
            protected Rectangle getImageBounds() {
                Rectangle bounds = new Rectangle(0, 0, 0, 0);
                if (img != null) {
                    bounds.setLocation(imgPoint);
                    bounds.setSize(img.getWidth(), img.getHeight());
                }
                return bounds;
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(65, 65);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (img != null) {
                    Graphics2D g2d = (Graphics2D) g.create();
                    g2d.drawImage(img, imgPoint.x, imgPoint.y, this);
                    g2d.dispose();
                }
            }
        }
    

提交回复
热议问题