简体   繁体   English

有没有办法可以将其放入for循环中?

[英]Is there a way I can stick this into a for loop?

I updated the code to use for loops, and an arrayList for the buttons. 我更新了代码以用于循环,并为按钮添加了arrayList。 now it has given me an error. 现在它给了我一个错误。

java.lang.NullPointerException java.lang.NullPointerException

BlueJ editor is pointing to this line. BlueJ编辑器指向这一行。

for(int i=0; i<=buttonsList.size(); i++){

I think it has something to do with instance variables not existing or something before the arrayList. 我认为这与不存在的实例变量或arrayList之前的东西有关。 Also, it compiles perfectly, but when I run main, it then goes back to the line in the code! 而且,它可以完美编译,但是当我运行main时,它又回到了代码行!

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

//Created class the extends JFrame, and implements action listener
public class Board extends JFrame implements ActionListener 
{
//Instance variables 
private JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, reset;
private ArrayList<JButton> buttonsList;

//'playerO' uses the letter 'O', not the number zero
Icon playerO = new ImageIcon("images/playerO.jpg");
Icon playerX = new ImageIcon("images/playerX.jpg");
Icon playerN = new ImageIcon("images/reset.jpg");

//Instance variable to determine player turn
boolean firstPlayer = true;

//Constructor
public Board()
{
    //Title of Frame
    super("Gui7 - TicTacToe || Jose Reyes");

    //Created container and set the layout
    Container c = getContentPane();
    c.setLayout(new BorderLayout());

    //Created a panel, and set the layout
    JPanel gridPanel = new JPanel();
    gridPanel.setLayout(new GridLayout(3,3));

    //Created new JButtons and added them to the array list 
    for(int i=0; i<=buttonsList.size(); i++){
        JButton jBut = new JButton(playerN);
        buttonsList.add(jBut);
    }

    //Created reset button and title
    reset = new JButton("Play Again?");

    //Added buttons to panel with for loop
    for(int i=0; i<=buttonsList.size(); i++){
        gridPanel.add(buttonsList.get(i));
    }

    //Added panel and reset button to container
    c.add(gridPanel);
    c.add(reset, BorderLayout.PAGE_END);

    //Added Action Listeners with loop
    for(int i=0; i<=buttonsList.size(); i++){
        buttonsList.get(i).addActionListener(this);
    }

    //Added action listener to reset button
    reset.addActionListener(this);

    //Set the window size and set visibility
    setSize(600,600);
    setVisible(true);
}

//ActionEvents
public void actionPerformed(ActionEvent e)
{
    //Grab source
    Object src = e.getSource();

    for (int i = 0; i<=buttonsList.size(); i++){
        if(src == buttonsList.get(i)){
            if(firstPlayer){
                buttonsList.get(i).setIcon(playerO);
                firstPlayer = false;
            } else {
                buttonsList.get(i).setIcon(playerX);
                firstPlayer = true;
            }
        }
    }


    //Reset button icons with loop
    if(src == reset){
        for (int i = 0; i < 9; i++){
            buttonsList.get(i).setIcon(playerN);
        }

        firstPlayer = true;
    }

}

//Main method
public static void main (String args[])
{
    Board t = new Board();
    t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Rather than have a bunch of variables named b1 ... b9 , make an array of whatever type b1 is. 而不是创建一堆名为b1 ... b9的变量,而是创建一个类型为b1的数组。 Then you can iterate over the array like this: 然后,您可以像这样遍历数组:

for (int i = 0; i < 9; i++){
    if(src == bArray[i]){
       if(firstPlayer){
          bArray[i].setIcon(playerO);
          firstPlayer = false;
       } else {
          bArray[i].setIcon(playerX);
          firstPlayer = true;
       }
    }
}

Yes you can do this with a for loop. 是的,您可以使用for循环执行此操作。

First, store all your buttons in an array or arraylist. 首先,将所有按钮存储在数组或arraylist中。 Since the other answer is an array, I'll do arraylist. 由于另一个答案是数组,所以我将做arraylist。

ArrayList<Button> buttonsList = new ArrayList<>();
buttonsList.add(b1);
buttonsList.add(b2);

etc. Then, 等,然后

for (Button b: buttonsList){
    if (src == b) {
        if (firstPlayer) {
            b.setIcon(playerO);
            firstPlayer = false;
        } else {
            b.setIcon(playerX);
            firstPlayer = true;
        }
    }
}

EDIT: I suggest you just use an arraylist instead of array. 编辑:我建议您只使用arraylist而不是array。 Its much easier to work with since you don't need to specify a size before hand. 由于您无需事先指定尺寸,因此使用起来非常容易。

Instead of this line: 代替此行:

private JButton buttons[];

Do

private ArrayList<Button> buttonList = new Arraylist()<>;

Additionally change, 此外,

for(int i=0; i<10; i++){
        buttons[i] = new JButton(playerN);
}
//do this instead
for(int i=0; i<10; i++){
    JButton jBut = new JButton(playerN);
    buttonsList.add(jBut);
}

//Added buttons to panel with for loop
for(int i=0; i<10; i++){
    gridPanel.add(buttons[i]);
}
//Do this instead
//Added buttons to panel with for loop
for(int i=0; i<10; i++){
    gridPanel.add(buttonsList.get(i));
}

EDIT2: This is almost definitely causing one of your problems lol EDIT2:这几乎肯定会引起您的问题之一

//Added Action Listeners with loop
for(int i=0; i<10; i++){
    buttons[1].addActionListener(this);
}

You are adding the listener to the second button- buttons[1] every time. 每次都将监听器添加到第二个button- button [1]。 Change that to buttons[i].addActionListener(this); 将其更改为button [i] .addActionListener(this); and it will probably work. 它可能会起作用。

something like below should work. 像下面这样的东西应该工作。

JButton[] buttons = new JButton[9]; // i'll leave you to fill it

for(int i = 0; i < buttons.length; i++){ // assuming the array is filled
 if(src == buttons[i]){
   if(firstPlayer){
      buttons[i].setIcon(playerO);
      firstPlayer = false;
   } else {
      buttons[i].setIcon(playerX);
      firstPlayer = true;
   }
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在TableLayout中将按钮相互粘贴? - How can I stick buttons to one another in TableLayout? 我可以通过哪种方式在Java中使用List写下for循环? - In which way I can write down for-loop with List in Java? 有没有办法可以使用 java 中的循环创建可变数量的 arrays? - Is there a way I can create a variable number of arrays using a loop in java? 如何去除白色背景,如何添加棍子? - How can I remove the white background and how can i add a stick? 简单的GUI指导。 我可以坚持使用BorderLayout还是需要其他东西? - Simple GUI guidance. Can I stick with BorderLayout or do I need something else? 有没有办法让我可以循环这个程序,在执行循环的一部分之后重新开始 - Is there a way that i can loop this program to start all over again after it executes part of a loop 如何将for循环的结果存储为java中的数组? 还有其他方法可以让我以简洁的方式编写此代码吗? - How to store results of for loop as an array in java? Is there any other way I can write this code neat way? Android:当我的应用程序处于后台时,如何检测自拍杆按钮点击 - Android: How can I detect selfie-stick button click when my app is in background 在被棒子击中后,如何使球去往应该去的地方? - How can I make the ball go where it is supposed to go after it is hit by the stick? 我无法绕着“用棍子男人画楼梯”程序 - I can't wrap my head around the “draw some stairs with stick-men” program
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM