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;
}
}
}
注意:我嘗試將JOptionPane調用更改爲System.exit(0),但這也不起作用,可能是因爲按鈕本身不工作。 – mcjcloud 2014-10-28 03:08:07