在 JPanel 顶部添加 JLabel

发布于 2024-12-13 18:10:00 字数 2428 浏览 2 评论 0原文

我尝试在 JPanel 顶部放置一个 .jpg 图标,以代表板上的一块板。我有一个包含 .java 文件的 GUI 文件夹和另一个包含 .jpg 文件的文件夹。

--主要编辑-- 示例代码

当单击一个正方形时,将放置一个白色图标,然后放置黑色等。这是我试图实现的一个非常基本的示例

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) {

}




}

I attempting to place a .jpg icon on top of a JPanel in order to represent a board piece on a board. I have a GUI folder with the .java files and another folder containing the .jpg files.

--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) {

}




}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一世旳自豪 2024-12-20 18:10:00

如果从容器中添加或删除组件,请不要忘记重新验证和重新绘制。我修改了您的 SSCCE,并且不再需要使用图像来使其可由无权访问您的图像文件的人(例如我!)运行。 // !! 注释指出了更改:

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) {

   }

}

类名也应该大写,并且您应该再次制作一次 ImageIcons。同样,一个 ImageIcon 可以由许多 JLabel 共享。您还需要响应 mousePressed 而不是 mouseClicked,因为 mouseClicked 可能很挑剔,特别是当您在按下和释放鼠标之间移动鼠标时。

希望您也看到了 SSCCE 的价值。 :)

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!). 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. Again, one ImageIcon can be shared by many JLabels. 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.

Hopefully you've also seen the value of an SSCCE. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文