简体   繁体   English

如何在 Java 中使用条件图标?

[英]How can I use an icon for a conditional in Java?

I'm working on a TicTacToe game with buttons that shows icons for each move.我正在开发一个 TicTacToe 游戏,其按钮显示每个动作的图标。 The issue is that there is no way I found to avoid a button being reused after a turn and the only way I found to avoid the reuse of the button is by setting and text and verifying if the button has that text or not (and then proceed to block the button or not).问题是我发现无法避免按钮在转弯后被重用,而我发现避免重用按钮的唯一方法是设置和文本并验证按钮是否具有该文本(然后是否继续阻止按钮)。 I would like to know if there is a way to use my icons for the conditional like for example: if the button has an x icon, then the button is blocked.我想知道是否有一种方法可以将我的图标用于条件,例如:如果按钮有一个 x 图标,则该按钮被阻止。 Something like that.类似的东西。

Here is my code:这是我的代码:

import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    
    /**
     *
     * @author ItzSebas
     */
    public class TTTApp extends javax.swing.JFrame {
    
        TicTacToe game = new TicTacToe();
        JButton board[][] = new JButton[3][3];
        int xScore;
        int oScore;
        int tieScore;
    
        public TTTApp() {
            initComponents();
            setTitle("Tic Tac Toe");
            setLocationRelativeTo(null);
            setResizable(false);
            setIconImage(new ImageIcon(getClass().getResource("/images/iconoPrograma.png")).getImage());
            UISetup();
        }
    
        public void UISetup(){
            board[0][0] = button1;
            board[0][1] = button2;
            board[0][2] = button3;
            board[1][0] = button4;
            board[1][1] = button5;
            board[1][2] = button6;
            board[2][0] = button7;
            board[2][1] = button8;
            board[2][2] = button9;
    
            ActionListener clickListener = new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    JButton selected = (JButton) e.getSource();
                    int ROW = 0;
                    int COLUMN = 0;
                    String valueButtonWithoutSpace = selected.getText().replace(" ", "");
    
                    if (valueButtonWithoutSpace == ""){
    
                        for (int i = 0; i < 3; i++) {
                            for (int j = 0; j < 3; j++) {
                                if (selected == board[i][j]) {
                                    ROW = i;
                                    COLUMN = j;
                                    break;
                                }
                            }
                        }
                        TicTacToeTile tile = new TicTacToeTile(ROW, COLUMN);
    
                        if(game.getCurrentTurn().name().equals("X")){
                            selected.setIcon(new ImageIcon(getClass().getResource("/images/xMove.png")));
                        }
                        else if(game.getCurrentTurn().name().equals("O")){
                            selected.setIcon(new ImageIcon(getClass().getResource("/images/oMove.png")));
                        }
                        //selected.setText(game.getCurrentTurn().name().equals("X") ? "X" : "O");
                        game.playTurn(tile.getRow(), tile.getColumn());
    
                        game.calculateResult();
    
                        if (game.isOver()) {
                            updateGameResults();
                            Boolean done = SafeInput.getYNConfirmDialog("Play Again?");
                            if (!done) {
                                System.exit(0);
                            }
                            resetGame();
                        }
                    }
                    else{
                        JOptionPane.showMessageDialog(null, "This button is already used. Pick another one!");
                    }
                }
            };
    
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    board[i][j].addActionListener(clickListener);
                }
            }
        }
    
        public void resetGame(){
            game.reset();
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    board[i][j].setText("");
                    board[i][j].setIcon(null);
                }
            }
        }
        public void updateGameResults(){
            if(game.getResult() == "X"){
                xScore += 1;
            }
            else if(game.getResult() == "O"){
                oScore += 1;
            }
            else if(game.getResult() == "Tie!"){
                tieScore += 1;
            }
            xWins.setText(""+xScore);
            oWins.setText(""+oScore);
        }
    
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
            jPanel2 = new javax.swing.JPanel();
            button7 = new javax.swing.JButton();
            button8 = new javax.swing.JButton();
            button9 = new javax.swing.JButton();
            button4 = new javax.swing.JButton();
            button5 = new javax.swing.JButton();
            button6 = new javax.swing.JButton();
            button3 = new javax.swing.JButton();
            button2 = new javax.swing.JButton();
            button1 = new javax.swing.JButton();
            jLabel3 = new javax.swing.JLabel();
            restartButton = new javax.swing.JButton();
            quitButton = new javax.swing.JButton();
            jPanel3 = new javax.swing.JPanel();
            oWins = new javax.swing.JLabel();
            xWins = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            player1Label = new javax.swing.JLabel();
            player2Label = new javax.swing.JLabel();
            titleLabel = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setLocation(new java.awt.Point(0, 0));
            setPreferredSize(new java.awt.Dimension(350, 600));
            setSize(new java.awt.Dimension(350, 600));
    
            jPanel1.setBackground(new java.awt.Color(247, 249, 248));
    
            jPanel2.setBackground(new java.awt.Color(247, 249, 248));
            jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    
            button7.setBackground(new java.awt.Color(247, 255, 255));
            button7.setBorderPainted(false);
            button7.setContentAreaFilled(false);
            button7.setFocusPainted(false);
            button7.setFocusable(false);
            jPanel2.add(button7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, 80, 80));
    
            button8.setBackground(new java.awt.Color(247, 255, 255));
            button8.setBorderPainted(false);
            button8.setContentAreaFilled(false);
            button8.setFocusPainted(false);
            button8.setFocusable(false);
            jPanel2.add(button8, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 200, 90, 80));
    
            button9.setBackground(new java.awt.Color(247, 255, 255));
            button9.setBorderPainted(false);
            button9.setContentAreaFilled(false);
            button9.setFocusPainted(false);
            button9.setFocusable(false);
            jPanel2.add(button9, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 200, 90, 80));
    
            button4.setBackground(new java.awt.Color(247, 255, 255));
            button4.setFont(new java.awt.Font("Segoe UI", 0, 3)); // NOI18N
            button4.setBorderPainted(false);
            button4.setContentAreaFilled(false);
            button4.setFocusPainted(false);
            button4.setFocusable(false);
            jPanel2.add(button4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 110, 80, 80));
    
            button5.setBackground(new java.awt.Color(247, 255, 255));
            button5.setBorderPainted(false);
            button5.setContentAreaFilled(false);
            button5.setFocusPainted(false);
            button5.setFocusable(false);
            jPanel2.add(button5, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 110, 90, 80));
    
            button6.setBackground(new java.awt.Color(247, 255, 255));
            button6.setBorderPainted(false);
            button6.setContentAreaFilled(false);
            button6.setFocusPainted(false);
            button6.setFocusable(false);
            jPanel2.add(button6, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 110, 90, 80));
    
            button3.setBackground(new java.awt.Color(247, 255, 255));
            button3.setBorderPainted(false);
            button3.setContentAreaFilled(false);
            button3.setFocusPainted(false);
            button3.setFocusable(false);
            jPanel2.add(button3, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 20, 90, 80));
    
            button2.setBackground(new java.awt.Color(247, 255, 255));
            button2.setBorderPainted(false);
            button2.setContentAreaFilled(false);
            button2.setFocusPainted(false);
            button2.setFocusable(false);
            jPanel2.add(button2, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 20, 90, 80));
    
            button1.setBackground(new java.awt.Color(247, 255, 255));
            button1.setBorderPainted(false);
            button1.setContentAreaFilled(false);
            button1.setFocusPainted(false);
            button1.setFocusable(false);
            jPanel2.add(button1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 80, 80));
    
            jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/fondoTablero.png"))); // NOI18N
            jPanel2.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 308, -1));
    
            restartButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/restartIcon.png"))); // NOI18N
            restartButton.setBorderPainted(false);
            restartButton.setContentAreaFilled(false);
            restartButton.setFocusPainted(false);
            restartButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/restartPress.png"))); // NOI18N
            restartButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/images/restartHover.png"))); // NOI18N
            restartButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    restartButtonActionPerformed(evt);
                }
            });
    
            quitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exitButton.png"))); // NOI18N
            quitButton.setBorderPainted(false);
            quitButton.setContentAreaFilled(false);
            quitButton.setFocusPainted(false);
            quitButton.setFocusable(false);
            quitButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
            quitButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exitPress.png"))); // NOI18N
            quitButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exitHover.png"))); // NOI18N
            quitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quitButtonActionPerformed(evt);
                }
            });
    
            jPanel3.setBackground(new java.awt.Color(247, 249, 248));
            jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    
            oWins.setFont(new java.awt.Font("Calibri", 1, 14)); // NOI18N
            oWins.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
            jPanel3.add(oWins, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 10, 20, 20));
    
            xWins.setFont(new java.awt.Font("Calibri", 1, 14)); // NOI18N
            xWins.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
            jPanel3.add(xWins, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 20, 20));
    
            jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/scoreBoard.png"))); // NOI18N
            jLabel2.setText("-");
            jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
            jPanel3.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 90, 40));
    
            player1Label.setText("Player 1");
    
            player2Label.setText("  Player 2");
    
            titleLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/logo.png"))); // NOI18N
            titleLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addGap(70, 70, 70)
                                                    .addComponent(player1Label)
                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                    .addGap(2, 2, 2)
                                                    .addComponent(player2Label))
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addGap(20, 20, 20)
                                                    .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                                            .addGap(22, 22, 22)
                                                            .addComponent(restartButton)
                                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                            .addComponent(quitButton))
                                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                                            .addGap(16, 16, 16)
                                                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(12, 12, 12)
                                    .addComponent(titleLabel)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addGap(27, 27, 27)
                                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                            .addComponent(player1Label)
                                                            .addComponent(player2Label)))
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addGap(18, 18, 18)
                                                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGap(48, 48, 48)
                                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(6, 6, 6)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(restartButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(quitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(11, 11, 11))
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
    
            pack();
        }// </editor-fold>                        
    
        private void restartButtonActionPerformed(java.awt.event.ActionEvent evt) {
            resetGame();
        }
    
        private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {
            System.exit(0);
        }
    
        public static void main(String args[]) {
    
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TTTApp().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JButton button1;
        private javax.swing.JButton button2;
        private javax.swing.JButton button3;
        private javax.swing.JButton button4;
        private javax.swing.JButton button5;
        private javax.swing.JButton button6;
        private javax.swing.JButton button7;
        private javax.swing.JButton button8;
        private javax.swing.JButton button9;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JLabel oWins;
        private javax.swing.JLabel player1Label;
        private javax.swing.JLabel player2Label;
        private javax.swing.JButton quitButton;
        private javax.swing.JButton restartButton;
        private javax.swing.JLabel titleLabel;
        private javax.swing.JLabel xWins;
        // End of variables declaration                   
    }

Icons can be shared by multiple components.图标可以由多个组件共享。 So there is no need to create a new ImageIcon every time you click on a button.因此,无需每次单击按钮时都创建新的 ImageIcon。

Instead create an xIcon and oIcon in the constructor of your class to use in later processing.而是在 class 的构造函数中创建一个 xIcon 和 oIcon 以在以后的处理中使用。

When you click on a button you can then just use:当您单击一个按钮时,您可以使用:

Icon icon = selected.getIcon();

if (icon == null)
    // do something

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM