2011-12-26 5 views
-2

I have the following code:Как я могу заставить этот рабочий конструктор работать правильно?

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

public class TTT extends JFrame implements ActionListener { //DO NOT TOUCH!!! 

    //makes the array for the buttons 
    JButton spots[ ] = new JButton[ 9]; 
    //keeps track of who's turn it is 
    int turn = 0; 
    //lets it go again 
    boolean go = true; 
    //gets the images for the X's and O's 
    ImageIcon red = new ImageIcon("x.PNG"); 
    ImageIcon blue = new ImageIcon("o.PNG"); 
    ImageIcon blank = new ImageIcon("blank.PNG"); 

    public static void main (String []args) { 
     TTT frame = new TTT(); //DO NOT TOUCH!!! 
     frame.setVisible(true); 
    } 

    public TTT() { //DO NOT TOUCH!!! 
     //set the frame default properties 
     setTitle ("Tic Tac Toe"); 
     setSize (308, 308); 
     setLocationRelativeTo (null); 
     setResizable(false); 
     //register 'Exit upon closing' as a default close operation 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

     changeBkColor(); 
    } 

    private void changeBkColor() { 
     while (go) { 
      //declares some variables that we will use later 
      int newLine = 0; 
      int lineCount = 0; 
      //change background color to white 
      Container contentPane = getContentPane(); 
      contentPane.setBackground(Color.WHITE); 
      contentPane.setLayout(null); 
      //puts the buttons on the screen 
      for (int i = 0; i < spots.length; i++) { 
       //make it first appear as a blank image 
       spots[ i] = new JButton (blank); 
       //checks if it needs a new row 
       if (i == 3 || i == 6) { 
        newLine++; 
        lineCount = 0; 
       } 
       //sets the positions of the buttons 
       spots[ i].setBounds(lineCount*100, newLine*100, 100, 100); 
       //add it to the container 
       contentPane.add(spots[ i]); 
       spots[ i].addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) { 
/*** Line 62 ***/  public void run() { 
          //check button pressed 
          for (int i = 0; i < spots.length; i++) { 
           if(e.getSource()==spots[ i]) { 
            //check turn 
            if (turn%2==0) { 
             spots[ i].setIcon(red); 
            } else { 
            spots[ i].setIcon(blue); 
            } 
            //disable the button so it can't be re-pressed 
            spots[ i].removeActionListener(this); 
           } 
          } 
          turn++; 
          //checks for wins 
          for(int i = 0; i < 3; i++) { 
           if (spots[ i].getIcon()==red &&    //checks for verticle x win 
            spots[ i+3].getIcon()==red && 
            spots[ i+6].getIcon()==red) { 
             int again1 = JOptionPane.showConfirmDialog(null, "X Wins! Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION); 
             if (again1 == JOptionPane.YES_OPTION) { 
              go = true; 
             } if (again1 == JOptionPane.NO_OPTION) { 
              JOptionPane.showMessageDialog(null, "Okay then. Bye!"); 
              go = false; 
             } 
           }else if (spots[ i].getIcon()==blue &&  //checks for verticle o win 
              spots[ i+3].getIcon()==blue && 
              spots[ i+6].getIcon()==blue) { 
               int again2 = JOptionPane.showConfirmDialog(null, "O Wins! Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION); 
               if (again2 == JOptionPane.YES_OPTION) { 
                go = true; 
               } if (again2 == JOptionPane.NO_OPTION) { 
                JOptionPane.showMessageDialog(null, "Okay then. Bye!"); 
                go = false; 
               } 
           }else if (spots[ i*3].getIcon()==red && //checks for horizontal x win 
              spots[ (i*3)+1].getIcon()==red && 
              spots[ (i*3)+2].getIcon()==red) { 
               int again3 = JOptionPane.showConfirmDialog(null, "X Wins! Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION); 
               if (again3 == JOptionPane.YES_OPTION) { 
                go = true; 
               } if (again3 == JOptionPane.NO_OPTION) { 
                JOptionPane.showMessageDialog(null, "Okay then. Bye!"); 
                go = false; 
               } 
           }else if (spots[ i*3].getIcon()==blue && //checks for horizontal o win 
              spots[ (i*3)+1].getIcon()==blue && 
              spots[ (i*3)+2].getIcon()==blue) { 
               int again4 = JOptionPane.showConfirmDialog(null, "O Wins! Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION); 
               if (again4 == JOptionPane.YES_OPTION) { 
                go = true; 
               } if (again4 == JOptionPane.NO_OPTION) { 
                JOptionPane.showMessageDialog(null, "Okay then. Bye!"); 
                go = false; 
               } 
           }else if (spots[ i].getIcon()==red &&  //checks for diagnol x win 
              spots[ 4].getIcon()==red && 
              spots[ 8-i].getIcon()==red) { 
               int again5 = JOptionPane.showConfirmDialog(null, "X Wins! Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION); 
               if (again5 == JOptionPane.YES_OPTION) { 
                go = true; 
               } if (again5 == JOptionPane.NO_OPTION) { 
                JOptionPane.showMessageDialog(null, "Okay then. Bye!"); 
                go = false; 
               } 
           }else if (spots[ i].getIcon()==blue && //checks for diagnol o win 
              spots[ 4].getIcon()==blue && 
              spots[ 8-i].getIcon()==blue) { 
               int again6 = JOptionPane.showConfirmDialog(null, "O Wins! Do you want to play again?", "Play again?", JOptionPane.YES_NO_OPTION); 
               if (again6 == JOptionPane.YES_OPTION) { 
                go = true; 
               } if (again6 == JOptionPane.NO_OPTION) { 
                JOptionPane.showMessageDialog(null, "Okay then. Bye!"); 
                go = false; 
               } 
           } 
          } 
          lineCount++; 
         } 
        } 
       }); 
      } 
     } if (!go) { 
      System.exit(0); 
     } 
    } 
} 

мой компиляции ненавидит линию 62 - публичный аннулируются Run() {- и мне нужна помощь фиксируя его. Я скопировал и вставил строку для уже работающей программы, поэтому я не знаю, как она не работает. EDIT извините ребята, вот мои ошибки:

TTT.java:62: error: illegal start of expression 
        public void run() { 
        ^
TTT.java:62: error: illegal start of expression 
        public void run() { 
         ^
TTT.java:62: error: ';' expected 
        public void run() { 
           ^
+0

-1 для слепого копирования и вставки. Ваша ошибка довольно фундаментальна, поэтому я не думаю, что вы получите большую помощь, задав такие вопросы. Я рекомендую сначала найти хорошую книгу Java или учебник. – Maxpm

+2

Какая ошибка компилятора? Для справок в будущем вам не нужен пастебин для кода. Просто укажите код и любые соответствующие сообщения об ошибках в вопросе. @Maxpm: На самом деле я не против копирования и вставки, если OP включил ошибку компилятора в этот процесс. К сожалению, это не так. –

+0

Почему вы думаете, что это должно работать? Просто потому, что вы копируете его из рабочего кода? –

ответ

3

Похоже, что вы определили метод в другом объявлении метода, а именно run() в actionPerformed(ActionEvent e).

Это запрещено на Java.

Похоже, что у вас есть недоразумение в отношении объявления static void run(), это не конструктор; это объявление метода с возвращаемым типом void.

1

changeBkColor - это бесконечный цикл, поэтому после того, как конструктор называется frame.setVisible (true), никогда не вызывается. Может быть, проблема.

Смежные вопросы