嗨我是新來的java,我想我會嘗試製作一個遊戲,其中用戶實際上試圖自己解決8皇后問題。然而,它增加了難度,開始8個白嘴鴉,高達14個主教,然後8個皇后。初學者的簡單8車賽遊戲
我已經成功創建了棋盤。我的mouselistener有一個問題...棋盤上的每個方塊都是一個按鈕,點擊時我的意圖是該方塊會改變顏色以指示它被點擊,然後所有不能再次點擊的方塊也會改變以指示擺脫遊戲的廣場。
當正方形被點擊時,它似乎沒有執行任何操作。 對不起,我知道它的微不足道。 謝謝。
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class rooks extends JFrame implements MouseListener{
private final int BOARD_SIZE = 8;
private final int BOARD_SIZE_COLS = 8;
private final int BOARD_SIZE_ROWS = 8;
// private JTextField bottom = new JTextField("") ");
// private JLabel bannerl = new JLabel("The game");
// private JButton queens = new JButton(" Play Queens ");
private JButton rooks = new JButton(" Play Rooks ");
// private JButton bishops = new JButton(" Play Knights ");
private JButton[][] cboard = new JButton[BOARD_SIZE][BOARD_SIZE];
private JTextArea bottomtextarea = new JTextArea();
// constructor creating the chessboard
public rooks(){
this.setSize(500, 500);
this.setTitle("rooks");
// this.setIconImage();
// create JPanels and add JComponents
JPanel main = new JPanel(new BorderLayout());
this.setContentPane(main);
JPanel north = new JPanel();
north.setLayout(new GridLayout(1,3));
main.add(north, BorderLayout.NORTH);
// north.add(queens);
north.add(rooks);
// north.add(bishops);
JPanel south = new JPanel();
main.add(south, BorderLayout.SOUTH);
south.add(bottomtextarea);
bottomtextarea.setEditable(false);
bottomtextarea.setVisible(true);
// create grid (actual chessboard) and initialise each button with no char
JPanel chessBoard = new JPanel(new GridLayout(BOARD_SIZE, BOARD_SIZE));
main.add(chessBoard, BorderLayout.CENTER);
for (int i=0; i<BOARD_SIZE_ROWS; i++){
for(int j=0; j<BOARD_SIZE_COLS; j++){
cboard[i][j] = new JButton("");
chessBoard.add(cboard[i][j]);
// as it loops add colour to the board, if (i+j=even then white, otherwise black)
if ((i + j) % 2 == 0) {
cboard[i][j].setBackground(Color.black);
}
else {
cboard[i][j].setBackground(Color.white);
}
}
}
cboard[7][7].addMouseListener(this);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
System.out.print("it has been clicked");
}
void saySomething(String eventDescription, MouseEvent e) {
}
}
謝謝,我發佈後,我只是把它放在一個JButtons。我使用ActionListener並將其放入循環中,以便將其添加到所有按鈕。 – 2012-03-07 21:44:55