2014-10-28 151 views
0

由于某种原因,JOptionPane没有显示在ActionListner中,当我点击没收按钮时,这里是我的类,没有其他类参与。我尝试在其他地方使用optionPane,比如构造函数,它可以工作,但是如果点击“没收”按钮,我需要它来显示。我不知道为什么我的JOptionPane没有在这里显示

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

    public class GUI extends JFrame implements ActionListener 
    { 
     JButton tttSquare; 
     JButton forfeit; 

     JLabel whosTurn; 
     JLabel turnImage; 

     JOptionPane optionPane = new JOptionPane(); 

     boolean turn = true; 
     String redOrBlack = "draw"; 

     public GUI() 
     { 
      Container contentPane = getContentPane(); 
      setSize(750, 450); 
      setTitle("TicTacToe"); 
      setLocationRelativeTo(null); 
      contentPane.setLayout(null); 
      setVisible(true); 
      setDefaultCloseOperation(EXIT_ON_CLOSE); 
      contentPane.setBackground(Color.lightGray); 

      int xCord = 0; 
      int yCord = 0; 
      // build tic tac toe board 
      for(int rowCount = 0; rowCount < 3; rowCount++) 
      { 
       xCord = 0; 
       for(int squareCount = 0; squareCount < 3; squareCount++) 
       { 
        tttSquare = new JButton(); 
        tttSquare.setBackground(Color.white); 
        tttSquare.addActionListener(this); 
        contentPane.add(tttSquare); 
        tttSquare.setBounds(xCord + 60, yCord + 55, 100, 100); 
        xCord += 105; 
       } 
       yCord += 105; 
      } 
      whosTurn = new JLabel("X's TURN"); 
      contentPane.add(whosTurn); 
      whosTurn.setLocation(525, 225); 
      whosTurn.setSize(100, 200); 

      forfeit = new JButton(); 
      contentPane.add(forfeit); 
      forfeit.setText("Forfeit?"); 
      forfeit.setLocation(500 ,165); 
      forfeit.setSize(100, 100); 
      forfeit.setBackground(Color.red);  // edit in action listener                   
     } 

     //main method 
     public static void main(String args[]) 
     { 
      GUI g = new GUI(); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) 
     { 
      JButton clicked = (JButton) e.getSource(); 
      if(clicked == forfeit) 
      { 
       optionPane.showMessageDialog("Winner!"); 
      } 
      else if(turn) 
      { 
       clicked.setBackground(Color.red); 
       forfeit.setBackground(Color.black); 
       redOrBlack = "black"; 
       turn = false; 
      } 
      else 
      { 
       clicked.setBackground(Color.black); 
       forfeit.setBackground(Color.red); 
       redOrBlack = "red"; 
       turn = true; 
      } 
     } 

    } 
+0

注意:我尝试将JOptionPane调用更改为System.exit(0),但这也不起作用,可能是因为按钮本身不工作。 – mcjcloud 2014-10-28 03:08:07

回答

0

找到我的解决方案!在回顾了我使用JButtons的其他项目之后,我发现我忘记使用JButton.addActionListener(this);

希望这仍然可以为有问题的人提供参考!

相关问题