有 Java 编程相关的问题?

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

用于输出棋盘的按钮的java GridLayout

我是用Java编程的,还是个新手。在试验GUI基础知识时,我决定制作一个棋盘,所有64个单元格都是背景填充的JButtons实例。遗憾的是,当我试图编译代码时,只显示了两个按钮,而且两个按钮都没有颜色。我试图理解这个问题,但现在我似乎有点不知所措

package checkerboard;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;

public class Checkerboard extends JFrame {

public Checkerboard() {

    JButton black = new JButton("B");
    JButton white = new JButton("W");

            black.setBackground(Color.BLACK);
            white.setBackground(Color.WHITE);



    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(8, 8));
    p1.setSize(600, 600);

    for (int i = 0; i < 8; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < 4; j++) {
                p1.add(black);
                p1.add(white);
            }
        } else {
            for (int j = 0; j < 4; j++) {
                p1.add(white);
                p1.add(black);
            }
        }
    }
    super.add(p1);
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Checkerboard frame = new Checkerboard();
    frame.setTitle("Checkers");
    frame.setSize(600, 600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    }
}

在使用JPanel进行实验时,出于某种奇怪的原因,第27行出现了一个空指针异常


共 (3) 个答案

  1. # 1 楼答案

    问题是,黑白是JButton对象,不能将同一个对象多次添加到JPanel

    每次添加时都需要创建一个新的JButton。您可以在循环中动态地实例化它们

    for (int i = 0; i < 8; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < 4; j++) {
                p1.add(newButton("B", Color.Black));
                p1.add(newButton("W", Color.White));
            }
        } else {
            for (int j = 0; j < 4; j++) {
                p1.add(newButton("W", Color.White));
                p1.add(newButton("B", Color.Black));
           }
        }
    }
    

    只需添加一个方法即可

    private newButton(String label, Color background) {
        JButton button = new JButton(label);
        button.setBackground(background);
        return button;
    }
    
  2. # 2 楼答案

    我做了这件事,但根据HW做了更多。但我被告知要添加JPanel和Jbuttons:

    编写一个显示棋盘的程序,其中每个黑白单元格都是背景为黑色或白色的JButton,如下图所示。重要的在程序中包含创建实现ActionListener的侦听器类的功能

    以下是我目前所拥有的,但我被告知需要添加JPanel和JButtons:

    import java.awt.event.*;    
    import javax.swing.JButton;    
    import javax.swing.JFrame;
    
    public class CheckerBox2 extends JFrame    
      {    
        JFrame frame=new JFrame();
    
        public CheckerBox2()
        {
          frame.setSize(500, 500);    
          frame.setTitle("Original Checker Box");    
          //MessageLabel=new JLabel("Press button to add colors.");    
          frame.setLayout(new GridLayout(8, 8));
          for (int i=0; i<8; i++)
          {    
          for (int j=0; j<8; j++)    
          {    
          switch ((i+j)%2)    
          {    
          case 0:    
            addButton("red");    
            break;    
          case 1:    
            addButton("black");    
            break;    
          default:    
           break;    
          }      
        }
    
       }    
      }
    
      // addButton() is used to customize what the ActionListener object
    
      private void addButton(String color)    
      {    
        JButton button=new JButton();  
        switch (color)    
        {    
        case "red":    
          button.setBackground(Color.RED);    
          break;    
        case "black":    
          button.setBackground(Color.BLACK);
          break;    
        default:    
         break;    
        }    
        button.setOpaque(true);    
        button.setBorderPainted(false);    
        Command listener=new Command(color);    
        button.addActionListener(listener);    
        frame.add(button);    
      }
    
      //The Command object has its constructor read in that color and display it verbatim at the command line.
    
      private class Command implements ActionListener    
      {    
        private String color;    
        public Command(String c)    
        {    
          color=c;
        }
    
        public void actionPerformed(ActionEvent event)    
        {    
          System.out.println("Pressed "+ color + " button.");
        }    
      }
    
      public void run()    
        {    
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
          frame.setVisible(true);    
        }
    
      public static void main(String[] args)    
      {    
        CheckerBox2 box=new CheckerBox2();    
        box.run();    
      } 
    }
    
  3. # 3 楼答案

    这是因为您只使用JButton的一个实例对象作为黑色按钮,而只使用JButton的一个实例对象作为白色按钮,并且您正在越来越多地向JPanel p1添加相同的2个引用。因此,这将不起作用,您需要为电路板上的每个按钮创建一个对象。以下是你如何做到这一点:

    enter image description here

    JButton[] blackButtons = new JButton[4 * 8];
    JButton[] whiteButtons = new JButton[4 * 8];
    
    for(int i = 0; i < blackButtons.length; i++)
    {
        blackButtons[i] = new JButton("B");
        blackButtons[i].setBackground(Color.BLACK);
    }
    for(int i = 0; i < whiteButtons.length; i++)
    {
        whiteButtons[i] = new JButton("W");
        whiteButtons[i].setBackground(Color.WHITE);
    }
    

    然后你可以这样添加它们:

    for (int i = 0; i < 8; i++) {
        if (i % 2 == 0) {
            for (int j = 0; j < 4; j++) {
                p1.add(blackButtons[4 * i + j]);
                p1.add(whiteButtons[4 * i + j]);
            }
        } else {
            for (int j = 0; j < 4; j++) {
                p1.add(whiteButtons[4 * i + j]);
                p1.add(blackButtons[4 * i + j]);
            }
        }
    }
    
    add(p1);