将.wav和.png / .jpg文件添加到GUI

时间:2019-11-25 07:09:56

标签: java

我创建了一个简单的井字游戏GUI游戏。我想通过将按钮上显示的内容从仅文本“ X”和“ O”更改为精美的图形“ X”和“ O”(通过提供jpg或png文件)来扩展它,并且还使用.wav文件添加声音。

这是我的游戏代码:(它的工作原理非常完美。我只需要扩展方面的帮助即可。谢谢)

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


public class TicTacToeGUI implements ActionListener
{
   //Class constants
   private static final int WINDOW_WIDTH = 300;
   private static final int WINDOW_HEIGHT = 300;
   private static final int TEXT_WIDTH = 30;

   private static final String PLAYER_X = "X"; // player using "X"
   private static final String PLAYER_O = "O"; // player using "O"
   private static final String EMPTY = "";  // empty cell
   private static final String TIE = "T"; // game ended in a tie

   private String player;   // current player (PLAYER_X or PLAYER_O)

   private String winner;   // winner: PLAYER_X, PLAYER_O, TIE, EMPTY = in progress

   private int numFreeSquares; // number of squares still free

   private JMenuItem resetItem; // reset board

   private JMenuItem quitItem; // quit

   private JLabel gameText; // current message

   private JButton board[][]; // 3x3 array of JButtons

   private JFrame window = new JFrame("TIC-TAC-TOE"); 



    /**
       * Constructs a new Tic-Tac-Toe GUI board
       */

   public TicTacToeGUI()
   {
       setUpGUI(); // set up GUI
       setFields(); // set up other fields   
   }



  /**
   * Set up the non-GUI fields
   *
   */
   private void setFields() 
   {
       winner = EMPTY;
       numFreeSquares = 9;
       player = PLAYER_X;
   }

   /**
   * reset the game so we can start again.
   *
   */
   private void resetGame() 
   {
       // reset board
       for (int i = 0; i < 3; i++)
       {
           for (int j = 0; j < 3; j++)
           {
               board[i][j].setText(EMPTY);
               board[i][j].setEnabled(true);
           }
       }
       gameText.setText("Game in Progress: X's turn");
       // reset other fields
       setFields();
    }



 /**
   * Action Performed (from actionListener Interface).
   * (This method is executed when a button is selected.)
   *
   * @param the action event
   */

   public void actionPerformed(ActionEvent e)
   {
       // see if it's a menu item
       if(e.getSource() instanceof JMenuItem) 
       {
           JMenuItem select = (JMenuItem) e.getSource();
           if (select==resetItem)
           { 
               resetGame();// reset
               return;
           }
           System.exit(0);   // must be quit
       }

       // it must be a button
       JButton chose = (JButton) e.getSource();  // set chose to the button clicked
       chose.setText(player);     // set its text to the player's mark
       chose.setEnabled(false);   // disable button (can't choose it now)
       numFreeSquares--;

       //see if game is over 
       if(haveWinner(chose))
       {
           winner = player; // must be the player who just went
       }
       else if(numFreeSquares==0)
       {
           winner = TIE; // board is full so it's a tie 
       }

       // if have winner stop the game
       if (winner!=EMPTY) 
       {
           disableAll(); // disable all buttons
           // print winner
           String s = "Game over: ";
           if (winner == PLAYER_X) 
           {
               s += "X wins";
           } 
           else if (winner == PLAYER_O) 
           {
               s += "O wins";
           } 
           else if (winner == TIE) 
           {
               s += "Tied game";
           }   
           gameText.setText(s);
       } 
       else
       {
           // change to other player (game continues)
           if (player==PLAYER_X)
           {
               player=PLAYER_O;
               gameText.setText("Game in progress: O's turn");
           } 
           else
           {
               player=PLAYER_X;
               gameText.setText("Game in progress: X's turn");
           }
       }
   }


   /**
    * Returns true if filling the given square gives us a winner, and false
    * otherwise.
    *
    * @param Square just filled
    * 
    * @return true if we have a winner, false otherwise
    */
   private boolean haveWinner(JButton c) 
   {
       // unless at least 5 squares have been filled, we don't need to go any further
       // (the earliest we can have a winner is after player X's 3rd move).
       if(numFreeSquares>4) 
       {
           return false;
       }

       // find the square that was selected
       int row=0, col=0;

       outerloop: // a label to allow us to break out of both loops
       for (int i = 0; i < 3; i++) 
       {
           for (int j = 0; j < 3; j++)
           {
              if (c==board[i][j])
              { 
                  // object identity
                  row = i;
                  col = j;  //  row, col represent the chosen square
                  break outerloop; // break out of both loops
              }    
           }
       }

       // check row "row"
       if( board[row][0].getText().equals(board[row][1].getText()) && board[row][0].getText().equals(board[row][2].getText()) )
       {
           return true;
       }

       // check column "col"
       if (board[0][col].getText().equals(board[1][col].getText()) &&board[0][col].getText().equals(board[2][col].getText()) ) 
       {
           return true;
       }

       // if row=col check one diagonal
       if (row == col)
       {
          if( board[0][0].getText().equals(board[1][1].getText()) && board[0][0].getText().equals(board[2][2].getText()) ) 
          {
              return true;
          }
       }

       // if row=2-col check other diagonal
       if (row == 2-col)
       {
          if( board[0][2].getText().equals(board[1][1].getText()) && board[0][2].getText().equals(board[2][0].getText()) )
          {
              return true;
          }
       }

       // no winner yet
       return false;
   }


   /**
   * Disables all buttons (game over)
   */
   private void disableAll()
   {
       if (numFreeSquares==0) 
       {
           return; // nothing to do
       }

       int i, j;
       for (i = 0; i < 3; i++) {
           for (j = 0; j < 3; j++) {
              board[i][j].setEnabled(false);
           }
       }
   }

   /**
   * Set up the GUI
   *
   */
   private void setUpGUI()
   {

        // for control keys
        final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); 

        window.setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // set up the menu bar and menu
        JMenuBar menubar = new JMenuBar();
        window.setJMenuBar(menubar); // add menu bar to our frame

        JMenu fileMenu = new JMenu("Game"); // create a menu called "Game"
        menubar.add(fileMenu); // and add to our menu bar

        resetItem = new JMenuItem("Reset"); // create a menu item called "Reset"
        fileMenu.add(resetItem); // and add to our menu (can also use ctrl-R:)
        resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, SHORTCUT_MASK));
        resetItem.addActionListener(this); 

        quitItem = new JMenuItem("Quit"); // create a menu item called "Quit"
        fileMenu.add(quitItem); // and add to our menu (can also use ctrl-Q:)
        quitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
        quitItem.addActionListener(this);

        window.getContentPane().setLayout(new BorderLayout()); // default so not required

        JPanel gamePanel = new JPanel();
        gamePanel.setLayout(new GridLayout(3, 3));
        window.getContentPane().add(gamePanel, BorderLayout.CENTER);

        gameText = new JLabel("Game in Progress: X's turn");
        window.getContentPane().add(gameText, BorderLayout.SOUTH);

        // create JButtons, add to window, and action listener
        board = new JButton[3][3];
        Font font = new Font("Dialog", Font.BOLD, 24);
        for (int i = 0; i < 3; i++)
        {
           for (int j = 0; j < 3; j++)
           {
              board[i][j] = new JButton(EMPTY);
              board[i][j].setFont(font);
              gamePanel.add(board[i][j]);
              board[i][j].addActionListener(this);
           }
        }

        window.setVisible(true);
   }

}

1 个答案:

答案 0 :(得分:0)

要将图像分配给JButton,可以使用构造函数或以下方法:

JButton myButton = new JButton(new ImageIcon("D:\\icon.png"));  

setIcon(new ImageIcon("D:\\icon.png"));

当然要提供您自己的文件路径。

要播放一些.wav声音,可以使用以下方法:

import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class MusicPlayer {

    private Clip clip;

    public void play() {

            try {
                AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:\\sound.wav").getAbsoluteFile());
                clip = AudioSystem.getClip();
                clip.open(audioInputStream);
                clip.start();
            }
            catch(Exception ex) {
                System.out.println("Error with playing sound.");
                ex.printStackTrace();
            }

    }
}