我正在尝试创建一个需要按如下方式设置的井字游戏 GUI:
1) 框架是由 2 个窗格组成的网格,左窗格带有 9 个按钮 grif,用作板 2) 右窗格窗格分为两个窗格 1 在另一个下方。根据用户使用单选按钮选择的符号,在游戏板上单击必须显示“X”或“O”。
由于我的鼠标侦听器代码在一个单独的类中,我不确定如何获得用户点击的内容。
这是我的代码。请在正确的方向上轻推我以克服此问题。
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package samples;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSplitPane;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
/**
*
* @author saikrishnan.srivat
*/
public class TicTacToe extends JFrame {
/*declare the components of the window*/
JPanel iconPanel;
JPanel tictactoeBoard;
JPanel emptyPanel;
JLabel chooseLabel;
JRadioButton xButton;
JRadioButton oButton;
ButtonGroup bg;
JButton resetButton;
JButton exitButton;
JButton undoButton;
JSplitPane rightPane;
JSplitPane pane;
MouseAdapterMod mam;
public TicTacToe() {
iconPanel = new JPanel();
tictactoeBoard = new JPanel();
emptyPanel = new JPanel();
chooseLabel = new JLabel("Choose your symbol :");
xButton = new JRadioButton("X");
oButton = new JRadioButton("O");
bg = new ButtonGroup();
bg.add(xButton);
bg.add(oButton);
/*add the label and the radio buttons too the empty panel*/
emptyPanel.add(chooseLabel);
emptyPanel.add(xButton);
emptyPanel.add(oButton);
emptyPanel.setLayout(new FlowLayout());
/*add the exit,undo and reset buttons to the icon panel*/
iconPanel.setLayout(new GridLayout(3, 1, 3, 3));
resetButton = new JButton("Reset");
exitButton = new JButton("Exit");
undoButton = new JButton("Undo Move");
iconPanel.add(resetButton);
iconPanel.add(exitButton);
iconPanel.add(undoButton);
/*Set layout of the tictactoe board and add the game buttons to it */
tictactoeBoard.setLayout(new GridLayout(3, 3));
/* Mouse adapter object that listens to the buttons in the tic tac toe board */
mam = new MouseAdapterMod();
for (int i = 0; i < 9; i++) {
JButton button = new JButton("");
button.addMouseListener(mam);
tictactoeBoard.add(button);
}
/*add the icon panel and the empty panel to the right pane*/
rightPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, iconPanel, emptyPanel);
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tictactoeBoard, rightPane);
add(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
//setMaximumSize(new Dimension(500, 500));
setMinimumSize(new Dimension(700, 500));
setLocationRelativeTo(null);
pack();
setTitle("Tic Tac Toe");
setLocationRelativeTo(null);
setVisible(true);
}
}
class MouseAdapterMod extends MouseAdapter {
/*Set 'X' or 'O' based the selected radio button- how to achieve this? */
public void mousePressed(MouseEvent e) {
//JButton button = (JButton)e.getSource();
//button.setText("");
}
}