IT序号网

java之我的 GUI 表现得很奇怪

mate10pro 2025年02月15日 编程语言 59 0

第一张图片显示了我刚启动时 GUI 的样子,第二张图片显示了当我在板上单击时发生的情况。在我单击棋子然后单击顶行的按钮后,棋子出现在顶行。这里发生了什么?!

代码如下;这个类是我拥有大部分代码的地方。其余的类此时只是加载图像。主要调用 Board 构造函数来构建 GUI。

public class  BoardPanel extends JPanel { 
 
public BoardPanel() {      
 
    createBoard(); 
 
} 
 
private void createBoard(){ 
 
    setLayout(new GridLayout(10, 10)); 
 
    // Makes a 10 x 10 grid of black and white colors 
    for (int i = 0; i<10; i++){ 
        for (int j = 0; j<10; j++){ 
            square[i][j] = new JButton(); 
            square[i][j].setRolloverEnabled(false); 
 
            if ((i+j)%2 == 0) 
                square[i][j].setBackground(Color.WHITE); 
 
            else  
                square[i][j].setBackground(Color.LIGHT_GRAY); 
 
            add(square[i][j]); 
        } 
    }                       
    addLabels(); 
    //Colors the corner squares 
    square[0][0].setBackground(new Color(155, 234, 242, 100)); 
    square[0][9].setBackground(new Color(155, 234, 242, 100)); 
    square[9][0].setBackground(new Color(155, 234, 242, 100)); 
    square[9][9].setBackground(new Color(155, 234, 242, 100));                       
} 
 
private void addLabels(){ 
    //Adds labels to the ranks 
    for  (int i =1 ; i< 9; i++){ 
        square[i][0].setBackground(new Color(155, 234, 242, 100));             
        square[i][0].setText(rank[8-i]); 
        square[i][0].setHorizontalTextPosition(SwingConstants.RIGHT); 
 
        square[i][9].setBackground(new Color(155, 234, 242, 100));                           
        square[i][9].setText(rank[8-i]); 
        square[i][9].setHorizontalTextPosition(SwingConstants.LEFT); 
 
} 
    //Adds labels to the files 
    for (int j = 1; j<9;j++){ 
        square[0][j].setBackground(new Color(155, 234, 242, 100)); 
        square[0][j].setText(file[j-1]);   
        square[0][j].setVerticalTextPosition(SwingConstants.BOTTOM); 
 
        square[9][j].setBackground(new Color(155, 234, 242, 100));             
        square[9][j].setText(file[j-1]); 
        square[9][j].setVerticalTextPosition(SwingConstants.TOP); 
    } 
JButton square[][] = new JButton[10][10]; 
String[] rank = {"1","2","3","4","5","6","7","8"}; 
String[] file = {"a","b","c","d","e","f","g","h"}; 
} 
} 

主类

public class Board { 
 
 
public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    frame.add(new BoardPanel()); 
    frame.setVisible(true); 
    frame.setSize(900, 700);       
 
    } 
 
} 

请您参考如下方法:

你的问题是按钮认为它是完全不透明的,而实际上它不是不透明的。根据 Kleopatra 在 this answer ,您必须使按钮不透明并接管绘画机制

        square[i][j] = new JButton() { 
           @Override  // !! add this: 
           protected void paintComponent(Graphics g) { 
              if (!isOpaque() && getBackground().getAlpha() < 255) { 
                 g.setColor(getBackground()); 
                 g.fillRect(0, 0, getWidth(), getHeight()); 
             } 
             super.paintComponent(g); 
           } 
        }; 
        square[i][j].setRolloverEnabled(false); 
        square[i][j].setOpaque(false); // !! and also add this ******* 

作为旁注,我不会使用 JButtons 来解决此类问题,而是使用 JPanels,并将我的棋子作为 ImageIcons 显示在 JLabels 中,添加到或从中删除的标签适当的棋盘方 block 。


没有按钮且没有使用 alpha 颜色的面板:

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import javax.swing.*; 
 
@SuppressWarnings("serial") 
public class Board2 extends JPanel { 
 
   private static final int SIDE_LEN = 80; 
   private static final Dimension SQUARE_SZ = new Dimension(SIDE_LEN, SIDE_LEN); 
   private static final Color EDGE_COLOR = new Color(165, 245, 250); 
   private static final Color DARK_SQR_COLOR = Color.LIGHT_GRAY; 
   private static final Color LIGHT_SQR_COLOR = Color.WHITE; 
   private JPanel[][] chessSquares = new JPanel[8][8];  
 
   public Board2() { 
      setLayout(new GridLayout(10, 10)); // sorry for magic numbers 
      for (int i = 0; i < 10; i++) { 
         for (int j = 0; j < 10; j++) { 
            if ((i == 0 || i == 9) && (j == 0 || j == 9)) { 
               add(createEdgePanel("")); 
            } else if (i == 0 || i == 9) { 
               String text = String.valueOf((char) (j + 'a' - 1)); 
               add(createEdgePanel(text)); 
            } else if (j == 0 || j == 9) { 
               String text = String.valueOf(8 - i + 1); 
               add(createEdgePanel(text)); 
            } else { 
               JPanel panel = createSquare(i, j); 
               add(panel); 
            } 
         } 
      } 
   } 
 
   private JPanel createSquare(int i, int j) { 
      JPanel panel = new JPanel(new GridBagLayout()); 
      Color c = (i % 2 == j % 2) ? LIGHT_SQR_COLOR : DARK_SQR_COLOR; 
      panel.setBackground(c); 
      panel.setPreferredSize(SQUARE_SZ); 
      panel.setBorder(BorderFactory.createLineBorder(Color.GRAY)); 
      return panel; 
   } 
 
   private JPanel createEdgePanel(String text) { 
      JLabel label = new JLabel(text, SwingConstants.CENTER); 
      JPanel panel = new JPanel(new GridBagLayout()); 
      panel.add(label); 
      panel.setBackground(EDGE_COLOR); 
      panel.setPreferredSize(SQUARE_SZ); 
      panel.setBorder(BorderFactory.createLineBorder(Color.GRAY)); 
      return panel; 
   } 
 
   private static void createAndShowGui() { 
      Board2 mainPanel = new Board2(); 
 
      JFrame frame = new JFrame("Board2"); 
      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(); 
         } 
      }); 
   } 
} 

在我的系统上看起来像:

现在添加了一些片段:

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 
import javax.imageio.ImageIO; 
import javax.swing.*; 
 
@SuppressWarnings("serial") 
public class Board2 extends JPanel { 
   private static final int SIDE_LEN = 80; 
   private static final Dimension SQUARE_SZ = new Dimension(SIDE_LEN, SIDE_LEN); 
   private static final String SPRITE_PATH = "http://i.stack.imgur.com/memI0.png"; 
   private static final int SPRITE_ROWS = 2; 
   private static final int SPRITE_COLS = 6; 
   private static final Color EDGE_COLOR = new Color(165, 245, 250); 
   private static final Color DARK_SQR_COLOR = Color.LIGHT_GRAY; 
   private static final Color LIGHT_SQR_COLOR = Color.WHITE; 
   private static final int ROWS = 8; 
   private JLabel[][] chessSquares = new JLabel[ROWS][ROWS];  
   private BufferedImage bigImage; 
   private List<Icon> icons = new ArrayList<>(); 
 
   public Board2() throws IOException { 
      URL imgUrl = new URL(SPRITE_PATH); 
      bigImage = ImageIO.read(imgUrl); 
      int w = bigImage.getWidth() / SPRITE_COLS; 
      int h = bigImage.getHeight() / SPRITE_ROWS; 
      for (int i = 0; i < SPRITE_ROWS; i++) { 
         for (int j = 0; j < SPRITE_COLS; j++) { 
            int x = (j * bigImage.getWidth()) / SPRITE_COLS; 
            int y = (i * bigImage.getHeight()) / SPRITE_ROWS; 
            BufferedImage spriteImg = bigImage.getSubimage(x, y, w, h); 
            Icon spriteIcon = new ImageIcon(spriteImg); 
            icons.add(spriteIcon); 
         } 
      } 
 
      for (int i = 0; i < chessSquares.length; i++) { 
         for (int j = 0; j < chessSquares[i].length; j++) { 
            chessSquares[i][j] = new JLabel(); 
         } 
      } 
 
      setLayout(new GridLayout(ROWS + 2, ROWS + 2)); // sorry for magic numbers 
      for (int i = 0; i < 10; i++) { 
         for (int j = 0; j < 10; j++) { 
            if ((i == 0 || i == ROWS + 1) && (j == 0 || j == ROWS + 1)) { 
               add(createEdgePanel("")); 
            } else if (i == 0 || i == ROWS + 1) { 
               String text = String.valueOf((char) (j + 'a' - 1)); 
               add(createEdgePanel(text)); 
            } else if (j == 0 || j == ROWS + 1) { 
               String text = String.valueOf(ROWS - i + 1); 
               add(createEdgePanel(text)); 
            } else { 
               JPanel panel = createSquare(i, j); 
               panel.add(chessSquares[i - 1][j - 1]); 
               add(panel); 
            } 
         } 
      } 
 
      setPieces(0, 0, 2); // rooks 
      setPieces(1, 0, 3); // knights 
      setPieces(2, 0, 4); // bishops 
 
      // kings and queens 
      chessSquares[0][3].setIcon(icons.get(1)); 
      chessSquares[7][3].setIcon(icons.get(6 + 1)); 
      chessSquares[0][4].setIcon(icons.get(0)); 
      chessSquares[7][4].setIcon(icons.get(6 + 0)); 
 
      // pawns 
      for (int i = 0; i < ROWS / 2; i++) { 
         setPieces(i, 1, 5); 
      } 
 
   } 
 
   private void setPieces(int colPos, int rowPos, int pieceIndex) { 
      chessSquares[rowPos][colPos].setIcon(icons.get(pieceIndex)); 
      chessSquares[rowPos][ROWS - 1 - colPos].setIcon(icons.get(pieceIndex)); 
      chessSquares[ROWS - 1 - rowPos][colPos].setIcon(icons.get(6 + pieceIndex)); 
      chessSquares[ROWS - 1 - rowPos][ROWS - 1 - colPos].setIcon(icons 
            .get(6 + pieceIndex)); 
   } 
 
   private void setPiece(int colPos, int pieceIndex) { 
      chessSquares[0][colPos].setIcon(icons.get(pieceIndex)); 
      chessSquares[ROWS - 1][ROWS - 1 - colPos].setIcon(icons.get(6 + pieceIndex)); 
   } 
 
   private JPanel createSquare(int i, int j) { 
      JPanel panel = new JPanel(new GridBagLayout()); 
      Color c = (i % 2 == j % 2) ? LIGHT_SQR_COLOR : DARK_SQR_COLOR; 
      panel.setBackground(c); 
      panel.setPreferredSize(SQUARE_SZ); 
      panel.setBorder(BorderFactory.createLineBorder(Color.GRAY)); 
      return panel; 
   } 
 
   private JPanel createEdgePanel(String text) { 
      JLabel label = new JLabel(text, SwingConstants.CENTER); 
      JPanel panel = new JPanel(new GridBagLayout()); 
      panel.add(label); 
      panel.setBackground(EDGE_COLOR); 
      panel.setPreferredSize(SQUARE_SZ); 
      panel.setBorder(BorderFactory.createLineBorder(Color.GRAY)); 
      return panel; 
   } 
 
   private static void createAndShowGui() { 
      Board2 mainPanel = null; 
      try { 
         mainPanel = new Board2(); 
      } catch (IOException e) { 
         e.printStackTrace(); 
         System.exit(-1); 
      } 
 
      JFrame frame = new JFrame("Board2"); 
      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(); 
         } 
      }); 
   } 
} 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!