如何使这些JButtons的JLabel不可见 [英] How Do I Make These JLabels of JButtons invisible

查看:163
本文介绍了如何使这些JButtons的JLabel不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 BoardSquare 的类,它是 JButton 的继承类。每个 BoardSquare 对象都存储在数组 BoardSquare [] [] boardsquares 中。我使用了以下代码

I have a class called BoardSquare that is an inherited class of JButton. Each of the BoardSquare objects is stored in an array BoardSquare[][] boardsquares. I have used the following code

BoardSquare.boardSquares [j] [i] .add(new JLabel((j + 1)+): +(i + 1)));

根据坐标为数组中的每个方块添加标签。我需要他们有这些标签(我认为),以便我可以识别它们和 addActionListeners 等。如何使JLabel不可见,以便它们不会出现在我的JFrame?

to add labels to each of the squares in the array according to their coordinates. I need them to have these labels(I think) so that I can identify them and addActionListeners, etc. How do I make the JLabels invisible so they don't show up in my JFrame?

或者,如何让每个按钮的JLabel成为一个实例变量,以便我可以调用 JLabel.setVisible(false)但是当我添加动作听众时仍然使用它们?

Alternatively, how can I make the JLabel of each button an instance variable so that I can call JLabel.setVisible(false) but still use them when I add action listeners?

编辑:如果有人有兴趣,那就是跳棋游戏。

If anyone's interested, it's for a Checkers Game.

以下是我的课程:

GameWindow

BoardSquare

Checker

MyListener

Here are my classes:
GameWindow
BoardSquare
Checker
MyListener

推荐答案

感谢您的编辑。如果这是我的应用程序,我可能会做非常不同的事情,包括,

Thank you for the edit. If this were my application, I'd probably do things very differently including,


  • 使用JLabels网格而不是JButtons。我认为没有必要使用JButton,并且问题在于按钮不像其他可能的解决方案那样具有视觉吸引力。

  • 给JLabel单元格或者包含JPanel一个MouseListener,

  • 让JPanel单元格没有Icon,因此如果没有检查器,则为空,

  • 或者让他们持有适当颜色的检查器的ImageIcon如果它们不是空的。

  • 您甚至可以通过使用玻璃窗格来保存带有用户可以拖动的相应检查器ImageIcon的JPanel来为GUI设置动画。

  • Use a grid of JLabels not JButtons. I see no need to use JButtons, and a problem in that the button would not be as visually appealing as other possible solutions.
  • Either give the JLabel cells or the containing JPanel a MouseListener,
  • Have the JPanel cells have no Icon and thus be empty if no checker is on them,
  • Or have them hold an ImageIcon of an appropriately colored checker if they are not empty.
  • You could even animate the GUI by using the glass pane to hold a JPanel with an appropriate checker ImageIcon that the user can drag.

请注意,如果您必须使用JButton,则不要向它们添加JLabel。而只需将JButton的Icon设置为null或适当的Checker ImageIcon。

Note that if you absolutely have to use JButtons, then don't add JLabels to them. Instead simply set the JButton's Icon to null or to an appropriate Checker ImageIcon.

编辑 < br>
例如,一个错误的代码示例作为概念证明。尝试编译并运行它。

Edit
For example, a bad code example as a proof of concept. Try compiling and running this.

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.EnumMap;
import java.util.Map;

import javax.swing.*;

@SuppressWarnings("serial")
public class Checkers extends JPanel {
   public static final int SIDE_LENGTH = 60;
   public static final int ROW_COUNT = 8;
   private static final String ROW = "row";
   private static final String COLUMN = "column";
   private static final Color LIGHT_COLOR = new Color(210, 180, 140);
   private static final Color DARK_COLOR = new Color(107, 68, 35);
   private Map<Checker, Icon> checkerIconMap = new EnumMap<Checker, Icon>(
         Checker.class);
   private JLabel[][] labelGrid = new JLabel[ROW_COUNT][ROW_COUNT];
   private Checker[][] checkerGrid = new Checker[ROW_COUNT][ROW_COUNT];

   public Checkers() {
      for (Checker checker : Checker.values()) {
         checkerIconMap.put(checker, createCheckerIcon(checker));
      }
      setLayout(new GridLayout(ROW_COUNT, ROW_COUNT));

      for (int row = 0; row < labelGrid.length; row++) {
         for (int col = 0; col < labelGrid[row].length; col++) {
            checkerGrid[row][col] = Checker.EMPTY;
            JLabel gridCell = new JLabel(checkerIconMap.get(Checker.EMPTY));
            gridCell.setOpaque(true);
            gridCell.putClientProperty(ROW, row);
            gridCell.putClientProperty(COLUMN, col);
            Color c = row % 2 == col % 2 ? LIGHT_COLOR : DARK_COLOR;
            gridCell.setBackground(c);
            add(gridCell);
            labelGrid[row][col] = gridCell;
         }
      }

      for (int i = 0; i < labelGrid.length / 2 - 1; i++) {
         for (int j = 0; j < labelGrid.length / 2; j++) {
            int row = i;
            int col = j * 2;
            col += row % 2 == 0 ? 1 : 0;
            labelGrid[row][col].setIcon(checkerIconMap.get(Checker.BLACK));
            checkerGrid[row][col] = Checker.BLACK;

            row = ROW_COUNT - row - 1;
            col = ROW_COUNT - col - 1;
            labelGrid[row][col].setIcon(checkerIconMap.get(Checker.RED));
            checkerGrid[row][col] = Checker.RED;
         }
      }

      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   private Icon createCheckerIcon(Checker checker) {
      BufferedImage img = new BufferedImage(SIDE_LENGTH, SIDE_LENGTH,
            BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = img.createGraphics();
      g2.setColor(checker.getColor());
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      int x = 3;
      int y = x;
      int width = SIDE_LENGTH - 2 * x;
      int height = width;
      g2.fillOval(x, y, width, height);
      g2.dispose();

      return new ImageIcon(img);
   }

   private class MyMouseAdapter extends MouseAdapter {
      private int selectedRow = -1;
      private int selectedCol = -1;
      private Checker selectedChecker = null;
      private JPanel glassPane = null;
      private Point p = null;
      private JLabel movingLabel = new JLabel(checkerIconMap.get(Checker.EMPTY));

      public MyMouseAdapter() {
         movingLabel.setSize(movingLabel.getPreferredSize());
         movingLabel.setVisible(false);
      }

      @Override
      public void mousePressed(MouseEvent e) {
         p = e.getPoint();
         for (int row = 0; row < labelGrid.length; row++) {
            for (int col = 0; col < labelGrid[row].length; col++) {
               JLabel gridCell = labelGrid[row][col];
               if (gridCell == getComponentAt(p)) {
                  if (checkerGrid[row][col] != Checker.EMPTY) {
                     selectedRow = row;
                     selectedCol = col;
                     selectedChecker = checkerGrid[row][col];
                     checkerGrid[row][col] = Checker.EMPTY;
                     labelGrid[row][col].setIcon(checkerIconMap.get(Checker.EMPTY));

                     JRootPane rootPane = SwingUtilities.getRootPane(Checkers.this);
                     glassPane = (JPanel) rootPane.getGlassPane();
                     glassPane.setVisible(true);
                     glassPane.setLayout(null);
                     movingLabel.setIcon(checkerIconMap.get(selectedChecker));
                     movingLabel.setVisible(true);
                     glassPane.add(movingLabel);
                     int x = p.x - SIDE_LENGTH / 2;
                     int y = p.y - SIDE_LENGTH / 2;
                     movingLabel.setLocation(x, y);
                  }
               }
            }
         }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         if (selectedChecker == null) {
            return;
         }

         p = e.getPoint();
         if (!Checkers.this.contains(p)) {
            // if mouse releases and is totally off of the grid
            returnCheckerToOriginalCell();
            clearGlassPane();
            return;
         }

         for (int row = 0; row < labelGrid.length; row++) {
            for (int col = 0; col < labelGrid[row].length; col++) {
               JLabel gridCell = labelGrid[row][col];
               if (gridCell == getComponentAt(p)) {
                  if (isMoveLegal(row, col)) {
                     checkerGrid[row][col] = selectedChecker;
                     labelGrid[row][col].setIcon(checkerIconMap.get(selectedChecker));

                     // todo: check for jumped pieces...
                  } else {
                     // illegal move
                     returnCheckerToOriginalCell();
                  }
               }
            }
         }
         clearGlassPane();
      }

      // this code would go in the model class
      private boolean isMoveLegal(int row, int col) {
         if (checkerGrid[row][col] != Checker.EMPTY) {
            // trying to put a checker on another checker
            returnCheckerToOriginalCell();
         } else if (row == selectedRow && col == selectedCol) {
            // trying to put checker back in same position
            returnCheckerToOriginalCell();
         } else if (row % 2 == col % 2) {
            // invalid square
            returnCheckerToOriginalCell();
         } else {
            // TODO: more logic needs to go here to test for a legal move
            // and to remove jumped pieces

            return true;
         }
         return false;
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         if (selectedChecker == null || p == null) {
            return;
         }
         p = e.getPoint();
         int x = p.x - SIDE_LENGTH / 2;
         int y = p.y - SIDE_LENGTH / 2;
         movingLabel.setLocation(x, y);
      }

      private void clearGlassPane() {
         glassPane.setVisible(false);
         movingLabel.setVisible(false);
         selectedChecker = null;
         p = null;
         selectedCol = -1;
         selectedRow = -1;
      }

      private void returnCheckerToOriginalCell() {
         checkerGrid[selectedRow][selectedCol] = selectedChecker;
         labelGrid[selectedRow][selectedCol].setIcon(checkerIconMap.get(selectedChecker));
      }
   }

   private static void createAndShowGui() {
      Checkers mainPanel = new Checkers();

      JFrame frame = new JFrame("JLabelGrid");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

class CheckerModel {

}

enum Checker {
   EMPTY(new Color(0, 0, 0, 0)), RED(Color.red), BLACK(Color.black);
   private Color color;

   private Checker(Color color) {
      this.color = color;
   }

   public Color getColor() {
      return color;
   }
}

更好的模型 - 视图示例正在进行...

Better Model-View example being worked on...

这篇关于如何使这些JButtons的JLabel不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆