简体   繁体   English

在JPanel之上添加JLabel

[英]Adding a JLabel on top of a JPanel

I attempting to place a .jpg icon on top of a JPanel in order to represent a board piece on a board. 我试图在JPanel顶部放置一个.jpg图标,以便在板上表示一块木板。 I have a GUI folder with the .java files and another folder containing the .jpg files. 我有一个包含.java文件的GUI文件夹和另一个包含.jpg文件的文件夹。

--Major Edit-- Example Code -主要编辑-示例代码

When a square is clicked a white icon is meant to be placed then black etc etc. This is a very basic example of what im trying to achieve 单击一个正方形时,应放置一个白色图标,然后放置一个黑色图标,等等。这是我试图实现的非常基本的示例

import java.awt.Dimension;

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

public class gui extends JFrame implements MouseListener {

/**
 * 
 */
private static final long serialVersionUID = -973341728129968945L;
JLayeredPane layeredPane;
JPanel board;
JLabel piece;
int numSquares;
private boolean currentPlayer;

public gui(){

    Dimension boardSize = new Dimension(600, 600);

    numSquares = 6;
    currentPlayer = true;

    layeredPane = new JLayeredPane();
    getContentPane().add(layeredPane);
    layeredPane.setPreferredSize(boardSize);
    layeredPane.addMouseListener(this);

    board = new JPanel();
    layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);

    board.setLayout( new GridLayout(numSquares, numSquares) );
    board.setPreferredSize( boardSize );
    board.setBounds(0, 0, boardSize.width, boardSize.height);

    for (int i = 0; i < (numSquares * numSquares); i++) {
        JPanel square = new JPanel( new BorderLayout() );
        square.setBorder(BorderFactory.createLineBorder(Color.black));
        square.setBackground(Color.green);
        board.add( square );


     }



}

public static void main(String[] args) {
        JFrame frame = new gui();
        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
        frame.pack();
        frame.setResizable(true);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
     }



@Override
public void mouseClicked(MouseEvent e) {
    JPanel temp =  (JPanel)board.findComponentAt(e.getX(), e.getY());
    System.out.println(e.getX() + " " + e.getY());

    if( currentPlayer ){
        ImageIcon white = new ImageIcon("l/Images/white.jpg");
        piece = new JLabel(white);
        temp.add(piece);
    }
    else{   
        ImageIcon black = new ImageIcon( "/Images/black.jpg");
        piece = new JLabel(black);
        temp.add(piece);
    }
    currentPlayer = !currentPlayer;


}


@Override
public void mouseEntered(MouseEvent e) {


}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e) {

}




}

Don't forget to revalidate and repaint if adding or removing components from a container. 如果要从容器中添加或删除组件,请不要忘记重新验证和重新绘制。 I've modified your SSCCE, and have gotten rid of the need to use images to make it runnable by folks who don't have access to your image files (like me!). 我已经修改了您的SSCCE,并且摆脱了使用图像的麻烦,使那些无法访问您的图像文件的人(例如我!)可以运行它。 Changes are noted by the // !! 更改由// !! comments: 评论:

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class Gui2 extends JFrame implements MouseListener {

   private static final long serialVersionUID = -973341728129968945L;
   JLayeredPane layeredPane;
   JPanel board;
   JLabel piece;
   int numSquares;
   private boolean currentPlayer;

   // !!
   private ImageIcon whiteIcon;
   private ImageIcon blackIcon;

   public Gui2() {
      // !!
      whiteIcon = createIcon(Color.white);
      blackIcon = createIcon(Color.black);

      Dimension boardSize = new Dimension(600, 600);

      numSquares = 6;
      currentPlayer = true;

      layeredPane = new JLayeredPane();
      getContentPane().add(layeredPane);
      layeredPane.setPreferredSize(boardSize);
      layeredPane.addMouseListener(this);

      board = new JPanel();
      layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);

      board.setLayout(new GridLayout(numSquares, numSquares));
      board.setPreferredSize(boardSize);
      board.setBounds(0, 0, boardSize.width, boardSize.height);

      for (int i = 0; i < (numSquares * numSquares); i++) {
         // !! JPanel square = new JPanel(new BorderLayout());
         JPanel square = new JPanel(new GridBagLayout()); // !!

         square.setBorder(BorderFactory.createLineBorder(Color.black));
         square.setBackground(Color.green);
         square.setName(String.format("[%d, %d]", i % numSquares, i
               / numSquares)); // !!
         board.add(square);

      }

   }

   // !!
   private ImageIcon createIcon(Color color) {
      int width = 40;
      int height = width;
      BufferedImage img = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = img.createGraphics();
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setColor(color);
      g2.fillOval(0, 0, width, height);
      g2.dispose();
      ImageIcon icon = new ImageIcon(img);
      return icon;
   }

   public static void main(String[] args) {
      JFrame frame = new Gui2();
      frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
      frame.pack();
      frame.setResizable(true);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   @Override
   // !!
   public void mousePressed(MouseEvent e) {
      JPanel temp = (JPanel) board.findComponentAt(e.getX(), e.getY());
      System.out.println(e.getX() + " " + e.getY());
      System.out.println(temp.getName()); // !!

      if (currentPlayer) {
         // !! ImageIcon white = new ImageIcon("l/Images/white.jpg");
         // !! piece = new JLabel(white);
         piece = new JLabel(whiteIcon); // !!
         temp.add(piece);
      } else {
         // !! ImageIcon black = new ImageIcon("/Images/black.jpg");
         // !! piece = new JLabel(black);
         piece = new JLabel(blackIcon); // !!
         temp.add(piece);
      }
      temp.revalidate(); // !!
      temp.repaint(); // !!
      currentPlayer = !currentPlayer;

   }

   @Override
   public void mouseEntered(MouseEvent e) {

   }

   @Override
   public void mouseExited(MouseEvent arg0) {
   }

   @Override
   public void mouseClicked(MouseEvent arg0) {
   }

   @Override
   public void mouseReleased(MouseEvent e) {

   }

}

Also class names should be capitalized, and also you should again make your ImageIcons once. 同样,类名也应大写,并且还应再次制作一次ImageIcons。 Again, one ImageIcon can be shared by many JLabels. 同样,一个ImageIcon可以被许多JLabel共享。 You'll also want to respond to mousePressed not mouseClicked as mouseClicked can be fussy, especially if you move the mouse between press down and mouse release. 您还需要响应mousePressed而不是mouseClicked,因为mouseClicked可能很挑剔,尤其是如果您在按下和释放鼠标之间移动了鼠标。

Hopefully you've also seen the value of an SSCCE. 希望您也已经看到了SSCCE的价值。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM