Как исправить метод getSource () для редактирования текста JButton в классе actionPerformed? - PullRequest
0 голосов
/ 16 января 2019

Мне нужно создать игру TicTacToe в апплете для школьного проекта в Ready to Program Java 1.42. В классе actionPerformed я хотел бы просто установить / отредактировать текст первого квадрата в левом верхнем углу на «X». Я использовал setActionCommand () в JButton и вызвал getActionCommand () в классе actionPerformed. Однако в моем операторе if я использую getSource (), поэтому могу ссылаться на сам объект и устанавливать / редактировать текст. Могу ли я не использовать getActionCommand () и getSource () вместе? Спасибо.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.JButton;

public class TicTacToe extends Applet implements ActionListener 
{
public void InitializeGame()
{

 setLayout(null);
 JButton Square1 = new JButton();
 Square1.setBackground(Color.white);
 Square1.setBounds(90,20,75,75);
 Square1.addActionListener(this);
 Square1.setActionCommand("s1");

 JButton Square2 = new JButton();
 Square2.setBackground(Color.white);
 Square2.setBounds(165,20,75,75);
 Square2.addActionListener(this);
 Square2.setActionCommand("s2");

 JButton Square3 = new JButton();
 Square3.setBackground(Color.white);
 Square3.setBounds(240,20,75,75);
 Square3.addActionListener(this);
 Square3.setActionCommand("s3");

 JButton Square4 = new JButton();
 Square4.setBackground(Color.white);
 Square4.setBounds(90,95,75,75);
 Square4.addActionListener(this);
 Square4.setActionCommand("s4");

 JButton Square5 = new JButton();
 Square5.setBackground(Color.white);
 Square5.setBounds(165,95,75,75);
 Square5.addActionListener(this);
 Square5.setActionCommand("s5");

 JButton Square6 = new JButton();
 Square6.setBackground(Color.white);
 Square6.setBounds(240,95,75,75);
 Square6.addActionListener(this);
 Square6.setActionCommand("s6");

 JButton Square7 = new JButton();
 Square7.setBackground(Color.white);
 Square7.setBounds(90,170,75,75);
 Square7.addActionListener(this);
 Square7.setActionCommand("s7");

 JButton Square8 = new JButton();
 Square8.setBackground(Color.white);
 Square8.setBounds(165,170,75,75);
 Square8.addActionListener(this);
 Square8.setActionCommand("s8");

 JButton Square9 = new JButton();
 Square9.setBackground(Color.white);
 Square9.setBounds(240,170,75,75);
 Square9.addActionListener(this);
 Square9.setActionCommand("s9");

 add(Square1);
 add(Square2);
 add(Square3);
 add(Square4);
 add(Square5);
 add(Square6);
 add(Square7);
 add(Square8);
 add(Square9);

}

public void init()
{
resize (400,300);
setBackground(Color.orange);

JButton Play = new JButton("Click to Play");                                 
Play.setBackground(Color.white);
Play.setForeground(Color.black);
Play.addActionListener(this);
add(Play);
}

public void actionPerformed(ActionEvent e)                         
{
removeAll();                                                       
setBackground(Color.pink);
InitializeGame();                                                   


if ( e.getActionCommand().equals( "s1" ) )
   {
   ((JButton)e.getSource()).setText("X");
   }

repaint(); 
} 

}

Я ожидаю увидеть «X» в левом верхнем углу JButton. Однако текст не отображается при запуске.

1 Ответ

0 голосов
/ 02 февраля 2019

Внутри actionPerformed() метода, вам нужно иметь removeAll(), setBackground() и InitializeGame() внутри блока if, как показано ниже:

В противном случае весь пользовательский интерфейс сбрасывается при каждом нажатии любой кнопки. (Потому что вы добавили один и тот же ActionListener ко всем кнопкам.)

public void actionPerformed(ActionEvent e)
{
  if (((JButton) e.getSource()).getText().equals("Click to Play")) {
    removeAll();
    setBackground(Color.pink);
    InitializeGame();
  }

  if ( e.getActionCommand().equals( "s1" ) )
  {
    ((JButton)e.getSource()).setText("X");
  }

  repaint();
}
...