询问java中关于jlabel和父级的一些说明

询问java中关于jlabel和父级的一些说明,java,swing,mouseevent,parent,jlabel,Java,Swing,Mouseevent,Parent,Jlabel,在互联网上发现了这段代码,它是几年前发布的,所以我决定在这里要求澄清一些我不太理解的行 在按住鼠标的方法中,他所说的是什么意思: chessPiece=null他是说如果JLabel chessPiece中有图像,那么应该将其更改为null IschessBoard.findComponentAt(e.getX(),e.getY())返回JPanel正方形 最后,当组件c得到它的父对象时,谁是父对象 整个代码如下: public class ChessGameDemo extends JFram

在互联网上发现了这段代码,它是几年前发布的,所以我决定在这里要求澄清一些我不太理解的行

在按住鼠标的
方法中,他所说的是什么意思:
chessPiece=null
他是说如果
JLabel chessPiece
中有图像,那么应该将其更改为
null

Is
chessBoard.findComponentAt(e.getX(),e.getY())
返回
JPanel
正方形

最后,当
组件c
得到它的父对象时,谁是父对象

整个代码如下:

public class ChessGameDemo extends JFrame implements MouseListener, MouseMotionListener {

    JLayeredPane layeredPane;
    JPanel chessBoard;
    JLabel chessPiece;
    int xAdjustment;
    int yAdjustment;
    private static final String imageFolderPath = "src/resources/images/";

    public ChessGameDemo() {
        Dimension boardSize = new Dimension(600, 600);

        //  Use a Layered Pane for this this application
        layeredPane = new JLayeredPane();
        getContentPane().add(layeredPane);
        layeredPane.setPreferredSize(boardSize);
        layeredPane.addMouseListener(this);
        layeredPane.addMouseMotionListener(this);

         //Add a chess board to the Layered Pane 
        chessBoard = new JPanel();
        layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
        chessBoard.setLayout(new GridLayout(8, 8));
        chessBoard.setPreferredSize(boardSize);
        chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);

        for (int i = 0; i < 64; i++) {
            JPanel square = new JPanel(new BorderLayout());
            chessBoard.add(square);

            int row = (i / 8) % 2;
            if (row == 0) {
                square.setBackground(i % 2 == 0 ? Color.blue : Color.white);
            } else {
                square.setBackground(i % 2 == 0 ? Color.white : Color.blue);
            }
        }

          //Add a few pieces to the board
        JLabel piece = new JLabel(new ImageIcon(imageFolderPath + "/pieces/bdg.png"));
        JPanel panel = (JPanel) chessBoard.getComponent(0);
        panel.add(piece);
        piece = new JLabel(new ImageIcon(imageFolderPath + "/pieces/belder.png"));
        panel = (JPanel) chessBoard.getComponent(15);
        panel.add(piece);
        piece = new JLabel(new ImageIcon(imageFolderPath + "/pieces/bhero.png"));
        panel = (JPanel) chessBoard.getComponent(16);
        panel.add(piece);
        piece = new JLabel(new ImageIcon(imageFolderPath + "/pieces/borb.png"));
        panel = (JPanel) chessBoard.getComponent(20);
        panel.add(piece);

    }

    public void mousePressed(MouseEvent e) {
        chessPiece = null;
        Component c = chessBoard.findComponentAt(e.getX(), e.getY());

        if (c instanceof JPanel) {
            return;
        }

        Point parentLocation = c.getParent().getLocation();
        xAdjustment = parentLocation.x - e.getX();
        yAdjustment = parentLocation.y - e.getY();
        chessPiece = (JLabel) c;
        chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
        chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
        layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
    }

        //Move the chess piece around
    public void mouseDragged(MouseEvent me) {
        if (chessPiece == null) {
            return;
        }
        chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
    }

         //Drop the chess piece back onto the chess board
    public void mouseReleased(MouseEvent e) {
        if (chessPiece == null) {
            return;
        }

        chessPiece.setVisible(false);
        Component c = chessBoard.findComponentAt(e.getX(), e.getY());

        if (c instanceof JLabel) {
            Container parent = c.getParent();
            parent.remove(0);
            parent.add(chessPiece);
        } else {
            Container parent = (Container) c;
            parent.add(chessPiece);
        }
        ....
    }
公共类ChessGameDemo扩展JFrame实现MouseListener、MouseMotionListener{
JLayeredPane layeredPane;
JPanel棋盘;
JLabel棋子;
内部调整;
内部调整;
私有静态最终字符串imageFolderPath=“src/resources/images/”;
公共棋局演示(){
尺寸板尺寸=新尺寸(600600);
//为此应用程序使用分层窗格
layeredPane=新的JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
layeredPane.addMouseListener(此);
layeredPane.addMouseMotionListener(此);
//将棋盘添加到分层窗格
棋盘=新JPanel();
layeredPane.add(棋盘,JLayeredPane.DEFAULT_层);
棋盘布局(新网格布局(8,8));
棋盘。设置首选大小(棋盘大小);
棋盘.立根(0,0,boardSize.width,boardSize.height);
对于(int i=0;i<64;i++){
JPanel square=newjpanel(newborderlayout());
棋盘。加(正方形);
int行=(i/8)%2;
如果(行==0){
正方形。背景(i%2==0?颜色。蓝色:颜色。白色);
}否则{
正方形。背景(i%2==0?颜色。白色:颜色。蓝色);
}
}
//在黑板上加几块
JLabel-piece=newjlabel(新的图像图标(imageFolderPath+“/pieces/bdg.png”);
JPanel面板=(JPanel)chessBoard.getComponent(0);
面板。添加(件);
工件=新的JLabel(新的图像图标(imageFolderPath+“/pieces/belder.png”);
panel=(JPanel)chessBoard.getComponent(15);
面板。添加(件);
piece=newjlabel(newimageicon(imageFolderPath+“/pieces/bhero.png”);
panel=(JPanel)chessBoard.getComponent(16);
面板。添加(件);
piece=newjlabel(newimageicon(imageFolderPath+“/pieces/borb.png”);
panel=(JPanel)chessBoard.getComponent(20);
面板。添加(件);
}
公共无效鼠标按下(MouseEvent e){
棋子=空;
组件c=chessBoard.findComponentAt(e.getX(),e.getY());
if(JPanel的c实例){
返回;
}
Point parentLocation=c.getParent().getLocation();
xAdjustment=parentLocation.x-e.getX();
yAdjustment=parentLocation.y-e.getY();
棋子=(JLabel)c;
chessPiece.setLocation(e.getX()+xaadjustment,e.getY()+yaadjustment);
chessPiece.setSize(chessPiece.getWidth(),chessPiece.getHeight());
layeredPane.add(棋子,JLayeredPane.DRAG_层);
}
//把棋子四处移动
公共无效鼠标标记(MouseEvent me){
如果(棋子==null){
返回;
}
chessPiece.setLocation(me.getX()+xaadjustment,me.getY()+yaadjustment);
}
//把棋子放回棋盘上
公共无效MouseEvent(MouseEvent e){
如果(棋子==null){
返回;
}
棋子。设置可见(假);
组件c=chessBoard.findComponentAt(e.getX(),e.getY());
if(JLabel的c实例){
容器父级=c.getParent();
父。删除(0);
添加(棋子);
}否则{
容器父项=(容器)c;
添加(棋子);
}
....
}
mousePiece
方法中,他所说的:
chessPiece=null
是什么意思 他说如果
JLabel棋子
中有图像,那么
是否应更改为
null

我假设您的意思是
mousePressed
。通过使用
chessPiece=null
,作者正在取消引用变量,因此无法通过is变量访问分配给它的内容

Is
chessBoard.findComponentAt(e.getX(),e.getY())
返回
JPanel
正方形

这取决于。
findComponentAt
可以搜索当前容器及其任何子容器,直到在指定位置找到组件。Technquial,作者忽略触发事件的组件(应该是
layeredPane
)我怀疑他们这样做是因为如果他们使用
layeredPane
它会返回
chessBoard

该方法能够返回
JPanel
JLabel
,甚至可能返回
null
,但考虑到组件的布局方式,这种可能性较低

最后,当组件c得到它的父对象时,谁是父对象

这要看情况。根据我对代码的理解,我会说它是在
JLabel
块下面返回一个
JPanel

不得不说,有更简单的方法来实现同样的结果,虽然

mousePiece
方法中,他所说的:
chessPiece=null
是什么意思 他说如果
JLabel棋子
中有图像,那么
是否应更改为
null

我猜你的意思是用棋子按下鼠标
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class ChessBoard extends JLayeredPane implements MouseListener, MouseMotionListener
{
    JLayeredPane layeredPane;
    JPanel chessBoard;
    JLabel chessPiece;
    int xAdjustment;
    int yAdjustment;

    public ChessBoard()
    {
        Dimension boardSize = new Dimension(600, 600);
        setPreferredSize( boardSize );

        //  Add a chess board to the Layered Pane

        chessBoard = new JPanel();
        chessBoard.setLayout( new GridLayout(8, 8) );
        chessBoard.setPreferredSize( boardSize );
        chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);
        chessBoard.addMouseListener( this );
        chessBoard.addMouseMotionListener( this );
        add(chessBoard, JLayeredPane.DEFAULT_LAYER);

        //  Build the Chess Board squares

        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                JPanel square = new JPanel( new BorderLayout() );
                square.setBackground( (i + j) % 2 == 0 ? Color.red : Color.white );
                chessBoard.add( square );
            }
        }

        // Add a few pieces to the board

        ImageIcon duke = new ImageIcon("dukewavered.gif"); // add an image here

        JLabel piece = new JLabel( duke );
        JPanel panel = (JPanel)chessBoard.getComponent( 0 );
        panel.add( piece );
        piece = new JLabel( duke );
        panel = (JPanel)chessBoard.getComponent( 15 );
        panel.add( piece );
    }

    /*
    **  Add the selected chess piece to the dragging layer so it can be moved
    */
    public void mousePressed(MouseEvent e)
    {
        chessPiece = null;
        Component c =  chessBoard.findComponentAt(e.getX(), e.getY());

        if (c instanceof JPanel) return;

        Point parentLocation = c.getParent().getLocation();
        xAdjustment = parentLocation.x - e.getX();
        yAdjustment = parentLocation.y - e.getY();
        chessPiece = (JLabel)c;
        chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);

        add(chessPiece, JLayeredPane.DRAG_LAYER);
        setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
    }

    /*
    **  Move the chess piece around
    */
    public void mouseDragged(MouseEvent me)
    {
        if (chessPiece == null) return;

        //  The drag location should be within the bounds of the chess board

        int x = me.getX() + xAdjustment;
        int xMax = chessBoard.getWidth() - chessPiece.getWidth();
        x = Math.min(x, xMax);
        x = Math.max(x, 0);

        int y = me.getY() + yAdjustment;
        int yMax = chessBoard.getHeight() - chessPiece.getHeight();
        y = Math.min(y, yMax);
        y = Math.max(y, 0);

        chessPiece.setLocation(x, y);
     }

    /*
    **  Drop the chess piece back onto the chess board
    */
    public void mouseReleased(MouseEvent e)
    {
        setCursor(null);

        if (chessPiece == null) return;

        //  Make sure the chess piece is no longer painted on the layered pane

        chessPiece.setVisible(false);
        remove(chessPiece);
        chessPiece.setVisible(true);

        //  The drop location should be within the bounds of the chess board

        int xMax = chessBoard.getWidth() - chessPiece.getWidth();
        int x = Math.min(e.getX(), xMax);
        x = Math.max(x, 0);

        int yMax = chessBoard.getHeight() - chessPiece.getHeight();
        int y = Math.min(e.getY(), yMax);
        y = Math.max(y, 0);

        Component c =  chessBoard.findComponentAt(x, y);

        if (c instanceof JLabel)
        {
            Container parent = c.getParent();
            parent.remove(0);
            parent.add( chessPiece );
            parent.revalidate();
        }
        else
        {
            Container parent = (Container)c;
            parent.add( chessPiece );
            parent.revalidate();
        }
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("Chess Board");
        frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
        frame.add( new ChessBoard() );
        frame.setResizable( false );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}