尝试使用JLayeredPane拖动某些内容

问题描述

我正在尝试将拖放操作放到我的程序中;我发现以下示例说明了我正在尝试做的很多事情:

    package sandBox;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.LayoutManager;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JlayeredPane;
    import javax.swing.JPanel;
    
    /**
     * Example showing the use of a JlayeredPane to implement dragging an object
     * across a JPanel containing other objects.
     * <P>
     * Basic idea: Create a JlayeredPane as a container,then put the JPanel containing
     * the application's components or whatever in the JlayeredPane.DEFAULT_LAYER layer of that layered pane.
     * The code is going to drag a JComponent object by calling JComponent.setPosition(x,y)
     * on the component. When a mouse is clicked on the panel to start the dragging,put the
     * component on the drag layer of the layered pane; as it is dragged,continue to call
     * setPosition to move it. When the mouse is released,use the x.y position of the release
     * to decide what to do with it next.   
     * 
     */
    public class ChessBoard extends JFrame implements MouseListener,MouseMotionListener
    {
      private static final long serialVersionUID = 1L;
        JlayeredPane layeredPane;
        JPanel chessBoard;
        JLabel chesspiece;
        int xAdjustment;
        int yAdjustment;
    
        public ChessBoard()
        {
            Dimension boardSize = new Dimension(600,600);
    
            //  Use a layered Pane for this application
    
            layeredPane = new JlayeredPane();
            layeredPane.setPreferredSize( boardSize );
            layeredPane.addMouseListener( this );
            layeredPane.addMouseMotionListener( this );
            getContentPane().add(layeredPane);
            
            //debug
            LayoutManager lm = layeredPane.getLayout();
            System.out.println("layered pane layout name is " + (lm == null? "<null>" : lm.getClass().getName()));
    
            //  Add a chess board to the layered Pane on the DEFAULT layer
            chessBoard = new JPanel();
            chessBoard.setLayout( new GridLayout(8,8) );
            chessBoard.setPreferredSize( boardSize );
            chessBoard.setBounds(0,boardSize.width,boardSize.height);
            layeredPane.add(chessBoard,JlayeredPane.DEFAULT_LAYER);
    
            //  Build the Chess Board squares
            // We use an 8x8 grid,and put a JPanel with BorderLayout on each square. 
            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.gray : Color.white );
                    chessBoard.add( square );
                }
            }
    
            // Add a few pieces to the board
            // we do this with an ImageIcon that gets added to the square's panel.
            ImageIcon duke = new ImageIcon("granary.gif");  // this is the image to add to each space.
            addDuke(duke,0);
            addDuke(duke,6);
            addDuke(duke,15);
            addDuke(duke,20);
        }
        
        private void addDuke(ImageIcon duke,int boardPosition)
        {
          JLabel pieceLabel = new JLabel(duke);
          JPanel piecePanel = (JPanel)chessBoard.getComponent(boardPosition);
          piecePanel.add(pieceLabel);
        }
    
        /*
        **  Add the selected chess piece to the dragging layer so it can be moved
        */
        public void mousepressed(MouseEvent e)
        {
          // get the component where the user pressed; iff that's not a panel,// we'll put it on the dragging layer.
            chesspiece = null;                                         // change1 swap the change1 lines
            // chesspiece = new JLabel(new ImageIcon("house1x1.gif")); // change1

            Component c =  chessBoard.findComponentAt(e.getX(),e.getY());
    
            if (c instanceof JPanel) return;
    
            // get the location of the panel containing the image panel,i.e.,// the square's panel. we adjust the location to which we move the
            // piece by this amount so the piece doesn't 'snap to' the cursor 
            // location.
            Point parentLocation = c.getParent().getLocation();
            xAdjustment = parentLocation.x - e.getX();
            yAdjustment = parentLocation.y - e.getY();
            chesspiece = (JLabel)c; // change2 - comment out
            chesspiece.setLocation(e.getX() + xAdjustment,e.getY() + yAdjustment);
    
            layeredPane.add(chesspiece,JlayeredPane.DRAG_LAYER); // evidently this removes it from the default layer also.
            layeredPane.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 = layeredPane.getWidth() - chesspiece.getWidth();
            x = Math.min(x,xMax);
            x = Math.max(x,0);
    
            int y = me.getY() + yAdjustment;
            int yMax = layeredPane.getHeight() - chesspiece.getHeight();
            y = Math.min(y,yMax);
            y = Math.max(y,0);
    
            chesspiece.setLocation(x,y);   // evidently this works for whatever layer contains the piece.
            // also,the layout manager of its new home is evidently not the same as lower layers.
         }
    
        /*
        **  Drop the chess piece back onto the chess board
        */
        public void mouseReleased(MouseEvent e)
        {
            layeredPane.setCursor(null);
    
            if (chesspiece == null) return;
    
            //  Make sure the chess piece is no longer painted on the layered pane
    
            chesspiece.setVisible(false);
            layeredPane.remove(chesspiece);
            chesspiece.setVisible(true);
    
            //  The drop location should be within the bounds of the chess board
    
            int xMax = layeredPane.getWidth() - chesspiece.getWidth();
            int x = Math.min(e.getX(),0);
    
            int yMax = layeredPane.getHeight() - chesspiece.getHeight();
            int y = Math.min(e.getY(),0);
    
            Component c =  chessBoard.findComponentAt(x,y);
            Container parent = null;
            if (c instanceof JLabel)
            {
                parent = c.getParent(); // there's a piece on the square already; remove it from the panel.
                parent.remove(0);
            }
            else
            {
                parent = (Container)c;
            }
            parent.add( chesspiece );     // this adds the piece back to the default layer
            parent.validate();
        }
    
        public void mouseClicked(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
    
        public static void main(String[] args)
        {
            JFrame frame = new ChessBoard();
            frame.setDefaultCloSEOperation( disPOSE_ON_CLOSE );
            frame.setResizable( false );
            frame.pack();
            frame.setLocationRelativeto( null );
            frame.setVisible(true);
         }
    }

这对于棋盘来说是可行的,即允许用户将棋盘上的任何棋子拖到另一个正方形上。

在我正在编写的应用程序中,要被拖动的项目不存在,直到用户单击启动拖动操作的内容为止。我在弄清楚如何进行创建并将其显示时遇到麻烦。

我当前的尝试是在标有“ change1”和“ change2”的行上进行;您将两行替换为“ change1”,并用“ change2”注释掉其中的一行。换句话说,在按下鼠标时创建JLabel,并(希望)拖动它。但是当我执行该操作时,图像在按下时或拖动过程中不会显示,但是确实会在拖动结束时显示在正方形上。

在这里错过了什么?我对JlayeredPane有点困惑,javadoc说它将遵循布局规则,但是布局规则是否适用于所有层上的所有组件,还是仅适用于底层,还是适用于所有层,但又分别适用于什么呢?我不认为这是布局问题,但我不知道出什么问题了。我需要在某处进行某种UI更新吗?我以为添加组件会使面板失效。

解决方法

原始代码是在您单击棋子的情况下编写的。

现在,您要单击一个空白单元格,这将需要进行以下更改。

  1. 国际象棋棋盘在每个单元格中均包含JPanel。一些单元格将包含代表棋子的JLabel。 mousePressed事件中的当前逻辑期望您单击JLabel,否则将跳过某些处理。

您需要删除:

//if (c instanceof JPanel) return;
  1. 默认情况下,Swing组件在创建时大小为0。

您需要给它一个尺寸:

chessPiece.setSize( chessPiece.getPreferredSize() );
  1. 标签的定位逻辑基于找到被单击的组件相对于父组件的位置。由于没有标签,因此此逻辑现在基于相对于分层窗格的面板。

您需要调整此逻辑以使其再次相对于父面板:

//Point parentLocation = c.getParent().getLocation();
Point parentLocation = c.getLocation();

我更新的mousePressed方法如下:

public void mousePressed(MouseEvent e)
{
  // get the component where the user pressed; iff that's not a panel,// we'll put it on the dragging layer.
    //chessPiece = null;                                         // change1 swap the change1 lines
    chessPiece = new JLabel(new ImageIcon("dukewavered.gif")); // change1
    chessPiece.setSize( chessPiece.getPreferredSize() );

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

    //if (c instanceof JPanel) return;

    // get the location of the panel containing the image panel,i.e.,// the square's panel. we adjust the location to which we move the
    // piece by this amount so the piece doesn't 'snap to' the cursor
    // location.
    //Point parentLocation = c.getParent().getLocation();
    Point parentLocation = c.getLocation();
    xAdjustment = parentLocation.x - e.getX();
    yAdjustment = parentLocation.y - e.getY();
    //chessPiece = (JLabel)c; // change2 - comment out
    chessPiece.setLocation(e.getX() + xAdjustment,e.getY() + yAdjustment);

    layeredPane.add(chessPiece,JLayeredPane.DRAG_LAYER); // evidently this removes it from the default layer also.
    layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}

请注意,以上更改将破坏能够拖动现有标签的旧功能。如果您需要同时使用这两种功能,那么将根据是单击JLabel(在这种情况下使用旧的逻辑)还是单击JPanel(在这种情况下使用新的逻辑)确定逻辑。