有 Java 编程相关的问题?

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

java在单击后分配变量值并删除JButtons

我已经为战列舰编写了一个工作脚本,该脚本适用于任何数量的战舰/网格行/网格列,以便在指定的位置进行分配。我已附上下面的工作代码。我现在想让玩家在游戏开始时通过点击相应的按钮来选择一个简单或困难的选项,这应该是: 将值分配给船舶(代码写为hits)、网格行和;网格列变量 从JFrame上卸下easy和hard按钮 然后让游戏继续下去

有人能建议怎么做吗

package battleshipswithinterface;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class BattleShipsWithInterface extends JFrame
{
    private static final String TITLE="Battleships";
    private static final int WINDOW_WIDTH = 400; //Window width
    private static final int WINDOW_HEIGHT = 200;  //Window height

    public static final int gridRowSize =6;
    public static final int gridColumnSize =5;
    public static final int numberOfButtons =gridRowSize*gridColumnSize;

    public int[] hits=new int[4];//location of ship
    public int hitSize=hits.length;
    public int shotHit;

    public int pressedColumn;
    public int pressedRow;
    public int hitRow;
    public int hitColumn;

    private Container content;
    private JButton[] buttons;
    private JButton initButton;
    private JLabel commentary;
    private JButton exitButton;

    //build a constructor
    public BattleShipsWithInterface()
    { 
        setTitle(TITLE);
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        content=getContentPane();
        content.setBackground(Color.BLACK);

        content.setLayout(new GridLayout((gridRowSize+1),gridColumnSize));
        buttons = new JButton[numberOfButtons]; //can we make Jbuttons 2D array?
        for (int i=0; i<numberOfButtons; i++)
        {
            buttons[i]=new JButton(" ");//(""+(i+1));
            buttons[i].putClientProperty("point",i);
            buttons[i].addActionListener((ActionListener) new ButtonsListener());
            content.add(buttons[i]);
        }

        initButton=new JButton("START AGAIN");
        initButton.addActionListener(new InitButtonListener());
        content.add(initButton);

        exitButton=new JButton("EXIT");
        exitButton.addActionListener(new ExitButtonListener());
        content.add(exitButton);

        commentary=new JLabel("Play Battleships!", SwingConstants.CENTER);
        commentary.setHorizontalAlignment(SwingConstants.CENTER);//could be 'setVerticalAlignment'??
        commentary.setForeground(Color.WHITE);
        commentary.setFont(new Font("Arial", Font.PLAIN,10));
        content.add(commentary);
        init();

    }
    public void init()
    {   
         Random random = new Random();
        for (int hit=0; hit<hitSize; hit++)
        {
            hits[hit]=random.nextInt(numberOfButtons);
            for (int check=0; check<hit; check++)
            {
                if (hits[hit]==hits[check])
                {
                    do 
                    {
                        hits[hit]=random.nextInt(numberOfButtons);
                    }
                    while (hits[hit]==hits[check]);    
                }
            }
        }   

        shotHit=0;

        setVisible(true); //display window  
        commentary.setText("Play Battleships!");

        for (int i=0; i<numberOfButtons; i++)
        {
            buttons[i].setText(" ");//(""+(i+1)); for alphabet!
        }  
    } 

    private class ButtonsListener implements ActionListener 
    {
        public void actionPerformed(ActionEvent e) 
        {
            JButton pressed=(JButton)(e.getSource());
            String text=pressed.getText();
            int index=((Integer) pressed.getClientProperty("point"))+1;

            int Remainder=index%gridColumnSize;
            if (Remainder==0)
            {
                pressedRow=index/gridColumnSize;
                pressedColumn=gridColumnSize;
            }
            else
            {
                pressedRow=((index-Remainder)/gridColumnSize)+1;
                pressedColumn=Remainder;
            }

            int row=0;
            int column=0;

            if (shotHit!=hitSize) ///consider taking this out - it may already be implied
            {
                if (text == "X")
                { 
                    commentary.setText("Already clicked!");
                    buttons[index-1].setText("X");    
                }
                else if (text=="*")
                {
                    commentary.setText("Already clicked!");
                    buttons[index-1].setText("*");
                }     
                else if (success(pressed))
                { 
                    shotHit++;
                    buttons[index-1].setText("*");
                    if (shotHit==hitSize)
                    {
                        commentary.setText("You Win!!!"); 
                    }
                }     
                else
                {
                    pressed.setText("X");
                    commentary.setText(" ");//could be better written if buttons indexed as 2D array

                    for (int k=0; k<hitSize; k++)
                    {

                        int hitRemainder=((hits[k]+1)%gridColumnSize);
                        if (hitRemainder==0)
                        {
                            hitRow=(hits[k]+1)/gridColumnSize;
                            hitColumn=gridColumnSize;
                        }
                        else
                        {
                            hitRow=(((hits[k]+1)-hitRemainder)/gridColumnSize)+1;
                            hitColumn=hitRemainder;
                        }
                        if (hitRow==pressedRow)
                        {
                            row++;
                        }
                        if (hitColumn==pressedColumn)
                        {
                            column++;
                        }
                        commentary.setText(column + " Ships in column " + pressedColumn +", "+ row + " ships in row " + pressedRow);

                    }
                }      
            }
        }
    }    

    public boolean success(JButton pressed)
    {
        int score=0;
        for (int q=0; q<hitSize; q++) 
        {
            if (pressed==buttons[hits[q]])
            {
                score++;
            }

        }
        if (score>0)
        {
            return true;
        }
        else 
        {
            return false;
        }
    }

    private class InitButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            init();
        }
    }

    private class ExitButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.exit(0);
        }
    }
    // create instance of GridWindow in main method
    public static void main(String[] args) 
    {
        BattleShipsWithInterface gui=new BattleShipsWithInterface();
    }

}

共 (2) 个答案

  1. # 1 楼答案

    我会为每个按钮使用不同的actionListener,这样更容易:

        buttons[i].addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                        for(int i=0;i<buttons.length;i++){
                                buttons[i].setVisible(false);
                        }
                        //rest of your code
                }
        });
    
  2. # 2 楼答案

    你也可以用

    buttons[i].setEnabled(false);
    

    这将使你的按钮冻结,不会让用户点击它