簡體   English   中英

JPanel對MouseEvents沒有反應嗎?

[英]JPanel doesn't react to MouseEvents?

我正在嘗試創建“井字游戲”。 我選擇創建JPanel的變體來表示每個正方形。 下面的類代表構成我的游戲板的9個面板之一。
現在我遇到的問題是,當我單擊面板時,面板內部應顯示“ X”,但什么也沒有發生。 如果有人引導我朝正確的方向前進,我將非常感激。

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

public class TicTacToePanel extends JPanel implements MouseListener {
    private boolean isPlayer1Turn = true;
    private boolean isUsed = false;
    private JLabel ticTacLbl = new JLabel();

    public TicTacToePanel() {
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e) {
        if (!isUsed) {
            if (isPlayer1Turn) {
                ticTacLbl.setForeground(Color.red);
                ticTacLbl.setText("X");
                add(ticTacLbl, 0);
                isUsed = true;
            } else {
                ticTacLbl.setForeground(Color.blue);
                ticTacLbl.setText("O");
                add(ticTacLbl, 0);
                isUsed = true;
            }

        } else {

        }
    }

    public void mousePressed(MouseEvent e) {

    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }

    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, new TicTacToePanel());
    }

}

編輯:
我只是在TicTacToePanel的構造函數中添加了標簽組件,所以不再需要調用revalidate(),並且在運行時不添加組件。

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

public class TicTacToePanel extends JPanel implements MouseListener{
    private boolean isPlayer1Turn = true;
    private boolean isUsed = false;
    private JLabel ticTacLbl = new JLabel();

    public TicTacToePanel(){
        add(ticTacLbl, 0);
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e){

    }

    public void mousePressed(MouseEvent e){
        if (!isUsed) {
            if (isPlayer1Turn) {
                ticTacLbl.setForeground(Color.red);
                ticTacLbl.setText("X");
                isUsed = true;
            } else {
                ticTacLbl.setForeground(Color.blue);
                ticTacLbl.setText("O");
                isUsed = true;
            }

        }
        else{

        }

    }

     public void mouseReleased(MouseEvent e){

    }

    public void mouseEntered(MouseEvent e){

    }

    public void mouseExited(MouseEvent e){

    }   

     public static void main(String[] args){
        JOptionPane.showMessageDialog(null, new TicTacToePanel());
    }
}

GUI構造函數:

     public TicTacToeGUI(int gameMode){
        if(gameMode == 0){
            amountOfPanels = 9;
            TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
            add(gamePanel, new GridLayout(3, 3));
            setPreferredSize(new Dimension(100, 100));
            for(int i = 0; i < amountOfPanels; i++){
                panelArr[i] = new TicTacToePanel();
                gamePanel.add(panelArr[i]);
            }   
        }
        else if(gameMode == 1){
            amountOfPanels = 225;
            TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
            add(gamePanel, new GridLayout(15, 15));
            setPreferredSize(new Dimension(500, 500));
            for(int i = 0; i < amountOfPanels; i++){
                panelArr[i] = new TicTacToePanel();
                gamePanel.add(panelArr[i]);
            }
        }

    }

    public static void main(String[] args){
        JOptionPane.showMessageDialog(null, new TicTacToeGUI(0));
    }
}

在運行時添加/刪除組件時,請始終在之后調用revalidate() revalidate()使組件刷新/重新布局。

因此,只需在添加標簽后調用revalidate()

如果您的目標是創建一個Tic Tac Toe游戲,那么您可能希望重新考慮您當前的動態向GUI添加組件的策略。 更好的方法是創建一個組件網格,例如JLabel,並在程序啟動時將其放置在JPanel上。 這樣,如果您希望在程序運行期間喜歡的話,可以更改按下的JLabel的文本和顏色,甚至其Icon,而不必添加或刪除組件。 例如:

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

@SuppressWarnings("serial")
public class TicTacToePanel extends JPanel {
    private static final int ROWS = 3;
    private static final int MY_C = 240;
    private static final Color BG = new Color(MY_C, MY_C, MY_C);
    private static final int PTS = 60;
    private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, PTS);
    public static final Color X_COLOR = Color.BLUE;
    public static final Color O_COLOR = Color.RED;
    private JLabel[][] labels = new JLabel[ROWS][ROWS];
    private boolean xTurn = true;

    public TicTacToePanel() {
        setLayout(new GridLayout(ROWS, ROWS, 2, 2));
        setBackground(Color.black);

        MyMouse myMouse = new MyMouse();
        for (int row = 0; row < labels.length; row++) {
            for (int col = 0; col < labels[row].length; col++) {
                JLabel label = new JLabel("     ", SwingConstants.CENTER);
                label.setOpaque(true);
                label.setBackground(BG);
                label.setFont(FONT);
                add(label);
                label.addMouseListener(myMouse);
            }
        }
    }

    private class MyMouse extends MouseAdapter {
        @Override // override mousePressed not mouseClicked
        public void mousePressed(MouseEvent e) {
            JLabel label = (JLabel) e.getSource();
            String text = label.getText().trim();
            if (!text.isEmpty()) {
                return;
            }
            if (xTurn) {
                label.setForeground(X_COLOR);
                label.setText("X");
            } else {
                label.setForeground(O_COLOR);
                label.setText("O");
            }

            // information to help check for win
            int chosenX = -1;
            int chosenY = -1;
            for (int x = 0; x < labels.length; x++) {
                for (int y = 0; y < labels[x].length; y++) {
                    if (labels[x][y] == label) {
                        chosenX = x;
                        chosenY = y;
                    }
                }
            }
            // TODO: check for win here
            xTurn = !xTurn;
        }
    }

    private static void createAndShowGui() {
        TicTacToePanel mainPanel = new TicTacToePanel();

        JFrame frame = new JFrame("Tic Tac Toe");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM