有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JButtons的java数组正在返回void

我正在尝试创建扫雷舰,我很早就被我的JButton数组卡住了,返回的是void而不是JButton,因此我无法对它执行任何操作

代码如下:(当我想删除按钮时,错误发生在最后一行)

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

public class Game extends JFrame implements ActionListener
{
   JButton[][] buttons;
   int rows;
   int cols;
   int x;
   int y;

   public Game(int rows, int cols)
   {
      setTitle("Minesweeper");
      setSize(500, 500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.rows = rows;
      this.cols = cols;
      setLayout(new GridLayout(rows, cols));
      buttons(rows, cols);
   }
   public void buttons(int tableX, int tableY)
   {

      buttons = new JButton[tableX][tableY];

      for (x = 0; x < tableX; x++)
      {
         for (y = 0; y < tableY; y++)
         {
            buttons[x][y] = new JButton(); 
            buttons[x][y].setActionCommand("Pressed");
            buttons[x][y].addActionListener(this);
            this.add(buttons[x][y]);            
         }
      }
   }
   public void actionPerformed(ActionEvent e)
   {
      for (x = 0; x < rows; x++)
      {
         for (y = 0; y < cols; y++)
         {
            if (e.getActionCommand().equals("Pressed"))
            {
               buttons[x][y] = setVisible(false);
            }
         }
      } 
   }
}

共 (3) 个答案

  1. # 1 楼答案

    你可能不想隐藏它们,你可以这样做

    buttons[x][y].setEnable(false);
    

    当您这样做时,您可以根据它们后面的内容更改它们上的图标

  2. # 2 楼答案

    使用.而不是=来调用方法

    buttons[x][y].setVisible(false);
    
  3. # 3 楼答案

    你确定setVisible()是一个独立的方法吗?试试buttons[x][y].setVisible(false);

    setVisible是属于JButton对象的方法,因此您不能随意调用它。思考“什么是设置为可见的?”

    当前,您得到了一个返回的void,因为当您想要调用JButton的setVisibile时,您实际调用的是立即类中名为setVisible()的方法(该方法不存在,因此返回void)