How to restart a program if a button is pressed in java? - java

I'm programing a game using JFrame, JPanel, JButton and actionListener and I'd like to have a button that when pressed restarts the game. Basically I want the the current Jframe to close and to reopen a new different one. I want it to be like a button you press to start a new game.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Start {
public static int a;
public static JButton[][] gumbi = new JButton[15][15];
public static JFrame okno = new JFrame("Nonogram");
public static void main(String[] args) {
okno.setVisible(true);
okno.setSize(800, 800);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
okno.add(panel);
JPanel polje = new JPanel(new GridLayout(15, 15));
panel.add(polje, BorderLayout.CENTER);
a = 0;
int b = 1;
// String I = I;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (i < 5 && j < 5) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.GREEN);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
} else if (i < 5 || j < 5) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.YELLOW);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
gumbi[i][j].setEnabled(false);
} else {
if (Math.random() <= 0.5) {
a += 1;
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].setForeground(Color.RED);
// gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("3");
polje.add(gumbi[i][j]);
} else {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].setForeground(Color.WHITE);
// gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("4");
polje.add(gumbi[i][j]);
}
}
}
}
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
gumbi[i][j].addActionListener(new Listener(gumbi));
}
}
int[] array = new int[105];
for (int i = 5; i < 15; i++) {
for (int j = 5; j < 15; j++) {
int num = Integer.parseInt(gumbi[i][j].getText());
array[j + ((i - 5) * 10) - 5] = num;
}
}
int[] array2 = new int[105];
for (int i = 0; i < 100; i++) {
array2[i] = -2;
}
for (int i = 0; i < 100; i++) {
if (array[i] == array[i + 1] && array[i] == 3 && (i + 1) % 10 != 0) {
b += 1;
} else if ((array[i] == 3 && array[i] != array[i + 1] && i < 99)
|| ((i + 1) % 10 == 0 && array[i] == 3)) {
array2[i] = b;
b = 1;
}
if ((i + 1) % 10 == 0) {
b = 1;
}
}
int x = 0;
int y = 0;
for (int i = 0; i <= 100; i++) {
// if(array2[(i-4) + (10*(j - 5))] != -2){
if (array2[i] != -2 && array[i] != 0) {
gumbi[x + 5][y].setText("" + array2[i]);
y++;
}
if ((i + 1) % 10 == 0) {
x++;
y = 0;
}
}
for (int i = 0; i < 101; i++) {
// System.out.println(array[i]);
if (array2[i] != -2)
System.out.print(array2[i] + " ");
}
for (int i = 5; i < 15; i++) {
for (int j = 5; j < 15; j++) {
int num = Integer.parseInt(gumbi[j][i].getText());
array[j + ((i - 5) * 10) - 5] = num;
}
}
for (int i = 0; i < 100; i++) {
array2[i] = -2;
}
b = 1;
for (int i = 0; i < 100; i++) {
if (array[i] == array[i + 1] && array[i] == 3 && (i + 1) % 10 != 0) {
b += 1;
} else if ((array[i] == 3 && array[i] != array[i + 1] && i < 99)
|| ((i + 1) % 10 == 0 && array[i] == 3)) {
array2[i] = b;
b = 1;
}
if ((i + 1) % 10 == 0) {
b = 1;
}
}
x = 0;
y = 0;
for (int i = 0; i <= 100; i++) {
if (array2[i] != -2 && array[i] != 0) {
gumbi[y][x + 5].setText("" + array2[i]);
y++;
}
if ((i + 1) % 10 == 0) {
x++;
y = 0;
}
}
System.out.println();
for (int i = 0; i < 105; i++) {
// System.out.println(array[i]);
if (array2[i] != -2)
System.out.print(array2[i] + " ");
}
System.out.println();
for (int i = 0; i < 105; i++) {
// System.out.println(array[i]);
System.out.print(array[i] + " ");
}
gumbi[1][1].setText("?");
gumbi[1][2].setText("C");
for (int i = 5; i < 15; i++) {
for (int j = 5; j < 15; j++) {
// gumbi[i][j].setText(null);
}
}
}
}
and the actionListener:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Listener implements ActionListener {
JButton[][] gumbi = Start.gumbi;
JFrame cestitke = new JFrame("Cestitke!");
JLabel bravo = new JLabel("Bravo, zmagali ste!");
JFrame vprasaj = new JFrame("Navodila");
JPanel navodila = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel restart = new JLabel("Za zaceti novo igro pritisnite tipko R(restart)");
JLabel pregled = new JLabel("Za pregled veljavnosti trenutne pozicije pritisnite tipko C(check)");
public Listener(JButton[][] gumbi) {
this.gumbi = gumbi;
}
public void actionPerformed(ActionEvent e) {
JButton gumb = (JButton) e.getSource();
if (gumb.getBackground() == Color.WHITE) {
gumb.setBackground(Color.BLACK);
} else if (gumb.getBackground() == Color.BLACK) {
gumb.setBackground(Color.WHITE);
}
if(e.getSource() == gumbi[1][1]){
vprasaj.setVisible(true);
vprasaj.setSize(450, 200);
vprasaj.add(navodila);
c.gridx = 0;
c.gridy = 0;
navodila.add(restart, c);
c.gridx = 0;
c.gridy = 1;
navodila.add(pregled, c);;
}
if(e.getSource() == gumbi[1][2]){
for(int i = 5; i < 15; i++){
for(int j = 5; j < 15; j++){
if(gumbi[i][j].getBackground() == Color.BLACK && gumbi[i][j].getForeground() == Color.WHITE){
gumbi[i][j].setBackground(Color.RED);
}
}
}
}
if(gumb.getBackground() == Color.RED && gumb.getForeground() == Color.WHITE){
gumb.setBackground(Color.WHITE);
}
if (gumb.getBackground() == Color.WHITE && gumb.getForeground() == Color.RED) {
Start.a += 1;
gumbi[0][0].setText("" + Start.a);
} else if (gumb.getBackground() == Color.BLACK && gumb.getForeground() == Color.RED) {
Start.a -= 1;
gumbi[0][0].setText("" + Start.a);
if(Start.a == 0){
for(int i = 5; i < 15; i++){
for (int j = 5; j < 15; j++){
gumbi[i][j].setEnabled(false);
}
}
cestitke.add(bravo);
cestitke.setVisible(true);
cestitke.setSize(100, 100);
}
}
if (gumb.getBackground() == Color.BLACK && gumb.getForeground() == Color.WHITE) {
Start.a += 100;
gumbi[0][0].setText("" + Start.a);
} else if (gumb.getBackground() == Color.WHITE && gumb.getForeground() == Color.WHITE) {
Start.a -= 100;
gumbi[0][0].setText("" + Start.a);
if(Start.a == 0){
for(int i = 5; i < 15; i++){
for (int j = 5; j < 15; j++){
gumbi[i][j].setEnabled(false);
}
}
cestitke.add(bravo);
cestitke.setVisible(true);
cestitke.setSize(100, 100);
}
}
}
}
thanks for your time.

Something like this?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.WindowEvent;
public class Start
{
public static int a;
public static JButton[][] gumbi = new JButton[15][15];
public static JFrame okno = null;
public static class Listener
implements ActionListener
{
JButton[][] gumbi = Start.gumbi;
JFrame cestitke = new JFrame("Cestitke!");
JLabel bravo = new JLabel("Bravo, zmagali ste!");
JFrame vprasaj = new JFrame("Navodila");
JPanel navodila = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel restart = new JLabel("Za zaceti novo igro pritisnite tipko R(restart)");
JLabel pregled = new JLabel("Za pregled veljavnosti trenutne pozicije pritisnite tipko C(check)");
public Listener(JButton[][] gumbi)
{
this.gumbi = gumbi;
}
public void actionPerformed(ActionEvent e)
{
JButton gumb = (JButton) e.getSource();
if (gumb.getBackground() == Color.WHITE)
{
gumb.setBackground(Color.BLACK);
}
else if (gumb.getBackground() == Color.BLACK)
{
gumb.setBackground(Color.WHITE);
}
if (e.getSource() == gumbi[1][1])
{
vprasaj.setVisible(true);
vprasaj.setSize(450, 200);
vprasaj.add(navodila);
c.gridx = 0;
c.gridy = 0;
navodila.add(restart, c);
c.gridx = 0;
c.gridy = 1;
navodila.add(pregled, c);;
}
if (e.getSource() == gumbi[1][2])
{
for (int i = 5; i < 15; i++)
{
for (int j = 5; j < 15; j++)
{
if (gumbi[i][j].getBackground() == Color.BLACK && gumbi[i][j].getForeground() == Color.WHITE)
{
gumbi[i][j].setBackground(Color.RED);
}
}
}
}
if (e.getSource() == gumbi[1][3])
{
restartFrame();
}
if (gumb.getBackground() == Color.RED && gumb.getForeground() == Color.WHITE)
{
gumb.setBackground(Color.WHITE);
}
if (gumb.getBackground() == Color.WHITE && gumb.getForeground() == Color.RED)
{
Start.a += 1;
gumbi[0][0].setText("" + Start.a);
}
else if (gumb.getBackground() == Color.BLACK && gumb.getForeground() == Color.RED)
{
Start.a -= 1;
gumbi[0][0].setText("" + Start.a);
if (Start.a == 0)
{
for (int i = 5; i < 15; i++)
{
for (int j = 5; j < 15; j++)
{
gumbi[i][j].setEnabled(false);
}
}
cestitke.add(bravo);
cestitke.setVisible(true);
cestitke.setSize(100, 100);
}
}
if (gumb.getBackground() == Color.BLACK && gumb.getForeground() == Color.WHITE)
{
Start.a += 100;
gumbi[0][0].setText("" + Start.a);
}
else if (gumb.getBackground() == Color.WHITE && gumb.getForeground() == Color.WHITE)
{
Start.a -= 100;
gumbi[0][0].setText("" + Start.a);
if (Start.a == 0)
{
for (int i = 5; i < 15; i++)
{
for (int j = 5; j < 15; j++)
{
gumbi[i][j].setEnabled(false);
}
}
cestitke.add(bravo);
cestitke.setVisible(true);
cestitke.setSize(100, 100);
}
}
}
}
public static void main(String[] args)
{
restartFrame();
}
public static void restartFrame()
{
if (null != okno)
{
okno.dispatchEvent(new WindowEvent(okno, WindowEvent.WINDOW_CLOSING));
okno = null;
}
okno = new JFrame("Nonogram");
okno.setVisible(true);
okno.setSize(800, 800);
okno.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
okno.add(panel);
JPanel polje = new JPanel(new GridLayout(15, 15));
panel.add(polje, BorderLayout.CENTER);
a = 0;
int b = 1;
// String I = I;
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
{
if (i < 5 && j < 5)
{
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.GREEN);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
}
else if (i < 5 || j < 5)
{
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.YELLOW);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
gumbi[i][j].setEnabled(false);
}
else
{
if (Math.random() <= 0.5)
{
a += 1;
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].setForeground(Color.RED);
// gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("3");
polje.add(gumbi[i][j]);
}
else
{
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].setForeground(Color.WHITE);
// gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("4");
polje.add(gumbi[i][j]);
}
}
}
}
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
{
gumbi[i][j].addActionListener(new Listener(gumbi));
}
}
int[] array = new int[105];
for (int i = 5; i < 15; i++)
{
for (int j = 5; j < 15; j++)
{
int num = Integer.parseInt(gumbi[i][j].getText());
array[j + ((i - 5) * 10) - 5] = num;
}
}
int[] array2 = new int[105];
for (int i = 0; i < 100; i++)
{
array2[i] = -2;
}
for (int i = 0; i < 100; i++)
{
if (array[i] == array[i + 1] && array[i] == 3 && (i + 1) % 10 != 0)
{
b += 1;
}
else if ((array[i] == 3 && array[i] != array[i + 1] && i < 99)
|| ((i + 1) % 10 == 0 && array[i] == 3))
{
array2[i] = b;
b = 1;
}
if ((i + 1) % 10 == 0)
{
b = 1;
}
}
int x = 0;
int y = 0;
for (int i = 0; i <= 100; i++)
{
if (array2[i] != -2 && array[i] != 0)
{
gumbi[x + 5][y].setText("" + array2[i]);
y++;
}
if ((i + 1) % 10 == 0)
{
x++;
y = 0;
}
}
for (int i = 0; i < 101; i++)
{
// System.out.println(array[i]);
if (array2[i] != -2)
{
System.out.print(array2[i] + " ");
}
}
for (int i = 5; i < 15; i++)
{
for (int j = 5; j < 15; j++)
{
int num = Integer.parseInt(gumbi[j][i].getText());
array[j + ((i - 5) * 10) - 5] = num;
}
}
for (int i = 0; i < 100; i++)
{
array2[i] = -2;
}
b = 1;
for (int i = 0; i < 100; i++)
{
if (array[i] == array[i + 1] && array[i] == 3 && (i + 1) % 10 != 0)
{
b += 1;
}
else if ((array[i] == 3 && array[i] != array[i + 1] && i < 99)
|| ((i + 1) % 10 == 0 && array[i] == 3))
{
array2[i] = b;
b = 1;
}
if ((i + 1) % 10 == 0)
{
b = 1;
}
}
x = 0;
y = 0;
for (int i = 0; i <= 100; i++)
{
if (array2[i] != -2 && array[i] != 0)
{
gumbi[y][x + 5].setText("" + array2[i]);
y++;
}
if ((i + 1) % 10 == 0)
{
x++;
y = 0;
}
}
System.out.println();
for (int i = 0; i < 105; i++)
{
// System.out.println(array[i]);
if (array2[i] != -2)
{
System.out.print(array2[i] + " ");
}
}
System.out.println();
for (int i = 0; i < 105; i++)
{
// System.out.println(array[i]);
System.out.print(array[i] + " ");
}
gumbi[1][1].setText("?");
gumbi[1][2].setText("C");
gumbi[1][3].setText("R");
}
}

Related

while loop in TICTACTOE game does not execute properly

I am a new to java programming and I am developing a simple a one player TICTACTOE game using swing. Thee are two classes. One main TICTACTOE class which uses an XOButtton class to set up buttons which can listen to click events. I begin by creating an object of this tictactoe class then use this object to call a method called initialCheckButton to find out if the buttons have been clicked 3 timess. If yes it calls another method to find out if the Xs or Os are consecutively displayed.If yes you win. I plan to develop this further but this is just a template. When the GUI dsiplays,clicking on buttons and display of successive Xs or Os does not display the message of the JoptionPane. Any help?
public class TicTacToe extends JFrame {
JPanel p = new JPanel();
boolean done = false;
XOButton buttons[] = new XOButton[9];
public static void main(String args[]) {
TicTacToe t = new TicTacToe();
t.initialCheckButton();
}
public TicTacToe() {
super("TicTacToe");
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
add(p);
setVisible(true);
}
public void initialCheckButton() {
int sum = 0;
while (sum <= 3) {
for (int i = 0; i < 9; i++) {
if (buttons[i].checkButtonO() == 1) {
sum++;
}
if (buttons[i].checkButtonX() == 1) {
sum++;
}
}
}
checkButtonFinal();
}
public void checkButtonFinal() {
for (int i = 0; i < 9; i++)
for (int j = i + 3; j < 9; j++) {
for (int k = j + 3; k < 9; k++) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
for (int i = 0; i < 9; i += 3) {
if (buttons[i].checkButtonO() == buttons[i + 1].checkButtonO() && buttons[i + 2].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[i + 1].checkButtonX() && buttons[i + 2].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
for (int i = 0; i < 9; i += 2) {
for (int j = i + 2; j < 9; j += 2)
for (int k = j + 2; k < 9; k += 2) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
for (int i = 0; i < 9; i += 4) {
for (int j = i + 4; j < 9; j += 4)
for (int k = j + 4; k < 9; k += 4) {
if (buttons[i].checkButtonO() == buttons[j].checkButtonO() && buttons[k].checkButtonO() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
if (buttons[i].checkButtonX() == buttons[j].checkButtonX() && buttons[k].checkButtonX() == 1)
JOptionPane.showMessageDialog(null, "Great, you won");
}
}
}
public static class XOButton extends JButton implements ActionListener {
public int buttonClicked = 0;
public int buttonClickedX = 0;
public int buttonClickedO = 0;
ImageIcon X, O;
byte value = 0;
/*
* 0:nothing 1:X 2:O
*/
public XOButton() {
X = new ImageIcon(this.getClass().getResource("X.png"));
O = new ImageIcon(this.getClass().getResource("O.png"));
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
value++;
value %= 3;
switch (value) {
case 0:
setIcon(null);
buttonClicked = 0;
break;
case 1:
setIcon(X);
buttonClickedX = 1;
break;
case 2:
setIcon(O);
buttonClickedO = 1;
break;
}
}
public int checkButtonO() {
return buttonClickedO;
}
public int checkButtonX() {
return buttonClickedX;
}
}
}
The following is a refactored version of your code that includes some documented changes :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class TicTacToe extends JFrame {
private static int ROW = 3, COLS = 3;
private final JPanel p;
private final XOButton buttons[];
//static counter, so it has the same value for all button instances
//used as a toggle between X and O
private static int counter = 0;
public static void main(String args[]) {
new TicTacToe();
}
public TicTacToe() {
super("TicTacToe");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
buttons = new XOButton[ROW*COLS];
p = new JPanel();
p.setLayout(new GridLayout(3, 3));
initialize();
add(p);
pack();
setVisible(true);
}
private void initialize(){
for (int i = 0; i < 9; i++) {
buttons[i] = new XOButton();
p.add(buttons[i]);
}
}
//restart game
private void restart(){
p.removeAll();
initialize();
revalidate();
}
private void checkButtons() {
//many similar for loops are not easy to follow
//refactor into methods
XOButton[] winningButtons = checkRows();
if( winningButtons != null) {
won(winningButtons);
}
winningButtons = checkCols();
if( winningButtons != null) {
won(winningButtons);
}
winningButtons = checkDIagonals();
if( winningButtons != null) {
won(winningButtons);
}
}
//returns winning buttons, or null
private XOButton[] checkRows() {
for(int row = 0; row < buttons.length ; row +=3 ){
int totalX = buttons[row].buttonClickedX + buttons[row+1].buttonClickedX+ buttons[row+2].buttonClickedX ;
int totalO = buttons[row].buttonClickedO + buttons[row+1].buttonClickedO+ buttons[row+2].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[row], buttons[row+1], buttons[row+2]};
}
return null;
}
//returns winning buttons, or null
private XOButton[] checkCols() {
for(int col = 0; col < COLS ; col++ ){
System.out.println(col+"-"+(col+3)+"-"+(col+6));
int totalX = buttons[col].buttonClickedX + buttons[col+3].buttonClickedX+ buttons[col+6].buttonClickedX ;
int totalO = buttons[col].buttonClickedO + buttons[col+3].buttonClickedO+ buttons[col+6].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[col], buttons[col+3], buttons[col+6]};
}
return null;
}
//returns winning buttons, or null
private XOButton[] checkDIagonals() {
int totalX = buttons[0].buttonClickedX + buttons[4].buttonClickedX+ buttons[8].buttonClickedX ;
int totalO = buttons[0].buttonClickedO + buttons[4].buttonClickedO+ buttons[8].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[0], buttons[4], buttons[8]};
totalX = buttons[2].buttonClickedX + buttons[4].buttonClickedX+ buttons[6].buttonClickedX ;
totalO = buttons[2].buttonClickedO + buttons[4].buttonClickedO+ buttons[6].buttonClickedO ;
if(totalX >=3 || totalO >=3) return new XOButton[]{buttons[2], buttons[4], buttons[6]};
return null;
}
//invoked when there is a winner
private void won(XOButton[] winningButtons) {
for(XOButton button : winningButtons){
button.setBackground(Color.PINK);
}
JOptionPane.showMessageDialog(null, "Great, you won");
restart(); //start new game
}
class XOButton extends JButton implements ActionListener {
private int buttonClicked = 0, buttonClickedX = 0, buttonClickedO = 0;
String X, O; //avoid using unavailable images when posting
public XOButton() {
X = "X";
O = "O";
this.addActionListener(this);
setPreferredSize(new Dimension(40,40));
}
#Override
public void actionPerformed(ActionEvent e) {
if(buttonClicked > 0 ) return; //invoke only on first click
buttonClicked ++;
counter = (counter+1)%2; //changes from 1 to 0 and back to 1
switch (counter) {
case 0:
setText(X);
buttonClickedX = 1;
break;
case 1:
setText(O);
buttonClickedO = 1;
break;
}
checkButtons();//check buttons after every click
}
public int checkButtonO() {
return buttonClickedO;
}
public int checkButtonX() {
return buttonClickedX;
}
}
}

Java: Using MouseListener to change the color of adjacent JButtons

I have a 15 x 15 2D array of JButton.
When I hold one of those buttons (i.e. Button[i][j]),
I would like to change the color of adjacent buttons (i.e. Button[i-1][j], Button[i+1][j], Button[i][j-1], Button[i][j+1]).
How do I do this?
Below is the part of my implementation of my 2D array. The button doesn't do anything for now.
fb = new JButton[15][15];
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
fb[i][j] = new JButton();
fb[i][j].setBackground(Color.WHITE);
fb[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
fb[i][j].setPreferredSize(new Dimension(40, 40));
//fb[i][j].setEnabled(false);
grid.add(fb[i][j]);
}
}
try this block:
if (i - 1 >= 0) {
if (fb[i - 1][j] != null) {
fb[i - 1][j].setBackground(Color.RED);
}
} else if (i + 1 < 15) {
if (fb[i + 1][j] != null) {
fb[i + 1][j].setBackground(Color.RED);
}
} else if (j - 1 >= 0) {
if (fb[i][j - 1] != null) {
fb[i][j - 1].setBackground(Color.RED);
}
} else if (j + 1 < 15) {
if (fb[i][j + 1] != null) {
fb[i][j + 1].setBackground(Color.RED);
}
}
and listener:
fb[i][j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
int x, y;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if(fb[i][j].equals(b)){
x = i;
y = j;
break;
}
}
}
if (x - 1 >= 0) {
if (fb[x - 1][y] != null) {
fb[x - 1][y].setBackground(Color.RED);
}
} else if (x + 1 < 15) {
if (fb[x + 1][y] != null) {
fb[x + 1][y].setBackground(Color.RED);
}
} else if (y - 1 >= 0) {
if (fb[x][y - 1] != null) {
fb[x][y - 1].setBackground(Color.RED);
}
} else if (y + 1 < 15) {
if (fb[x][y + 1] != null) {
fb[x][y + 1].setBackground(Color.RED);
}
}
}
});

Flagging Buttons for Minesweeper GUI Game

I have worked for hours on this code and finally gotten ver close to completion. I will be adding a Mine Counter and a timer once I figure out how to add the ability to flag mines with right clicking. I learned that JButtons do not recognize right clicks, so I must use a MouseEvent. From there, I'm lost. Can someone give me a nudge in the right direction?
This is what I currently have:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
public class MineSweeper implements ActionListener {
JFrame frame = new JFrame("Mine Sweeper");
JButton reset = new JButton("Reset");
JButton[][] buttons = new JButton[20][20];//button array
JButton[] flags = new JButton[20];
int[][] counts = new int[20][20];
Container grid = new Container(); //grid for buttons
int MineNum = 50;//number of mines
final int MINE = 10;//int value to identify a mine
public MineSweeper() {
frame.setSize(500, 500);
frame.setLayout(new BorderLayout());
frame.add(reset, BorderLayout.NORTH);
reset.addActionListener(this);
//Grid of Buttons
grid.setLayout(new GridLayout(20,20));
for (int a = 0; a<buttons.length; a++) {
for (int b = 0; b < buttons[0].length; b++) {
buttons[a][b] = new JButton("▒");
buttons[a][b].addActionListener(this);
buttons[a][b].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
mineFlagger(true);
}
}
});
grid.add(buttons[a][b]);
}
}
frame.add(grid, BorderLayout.CENTER);
makeRandomMines();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void mineFlagger (boolean flag){
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[0].length; j++) {
if(flag == true) {
buttons[i][j].setText("F");
}
}
}
}
public static void main(String[] args) {
new MineSweeper();
}
public void makeRandomMines() {
//initializes list of random pairs
ArrayList<Integer> list = new ArrayList<Integer>();
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
list.add(x * 100 + y);//changed y to x
}
}
//resets the counts in case reset button is pressed & picks random mines
counts = new int[20][20];
for (int i = 0; i < MineNum; i++) {
int choice = (int) (Math.random() * list.size());
counts[list.get(choice) / 100][list.get(choice) % 100] = MINE;
list.remove(choice);
}
//neighbor counts(how many mines are touching this square.)
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
int neighborCount = 0;
if (counts[x][y] != MINE) {
if(x > 0 && y > 0 && counts[x - 1][y - 1] == MINE) { //a mine is up & left
neighborCount++;
}
if(y > 0 && counts[x][y - 1] == MINE) { //a mine is up
neighborCount++;
}
if(x < counts.length - 1 && y > 0 && counts[x + 1][y - 1] == MINE) { // a mine is left
neighborCount++;
}
if(x > 0 && counts[x - 1][y] == MINE) { //left
neighborCount++;
}
if(x < counts.length - 1 && counts[x + 1][y] == MINE) { //mine is right
neighborCount++;
}
if(x > 0 && y < counts[0].length - 1 && counts[x - 1][y + 1] == MINE) { //mine is down
neighborCount++;
}
if(y < counts[0].length - 1 && counts[x][y + 1]== MINE) {//mine is up right
neighborCount++;
}
if(x < counts[0].length - 1 && y < counts[0].length - 1 && counts[x + 1][y + 1]== MINE) {//mine is down left
neighborCount++;
}
counts[x][y] = neighborCount;
}
}
}
}
public void lostGame() {
for (int x = 0; x < buttons.length; x++) {
for (int y = 0; y < buttons[0].length; y++) {
if (buttons[x][y].isEnabled()) {
if (counts[x][y] != MINE) {
buttons[x][y].setText(counts[x][y] + "");
buttons[x][y].setEnabled(false);
}
else {
buttons[x][y].setText("✪");
buttons[x][y].setEnabled(false);
}
}
}
}
JOptionPane.showMessageDialog(null, "You Lose!\n" + "You clicked on a mine!", "BOOM!", JOptionPane.INFORMATION_MESSAGE);
}
public void checkWin() {
boolean winner = true;
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
if (counts[x][y] != MINE && buttons[x][y].isEnabled()) {
winner = false;
}
}
}
if (winner == true) {
JOptionPane.showMessageDialog(frame, "You win!");
}
}
public void zeroCleaner(ArrayList<Integer> toClear) {
if (toClear.size() == 0) {
return;
}
else {
int x = toClear.get(0) / 100;
int y = toClear.get(0) % 100;
toClear.remove(0);
if(x > 0 && y > 0 && buttons[x-1][y-1].isEnabled()) { //up and left
buttons[x - 1][y - 1].setText(counts[x-1][y-1] + "");
buttons[x - 1][y - 1].setEnabled(false);
if (counts[x - 1][y - 1] == 0) {
toClear.add((x-1) * 100 + (y-1));
}
}
if (y > 0 && buttons[x][y-1].isEnabled()) { // up
buttons[x][y - 1].setText(counts[x][y-1] + "");
buttons[x][y - 1].setEnabled(false);
if (counts[x][y - 1] == 0) {
toClear.add(x * 100+(y - 1));
}
}
if (x < counts.length - 1 && y > 0 && buttons[x+1][y-1].isEnabled()) { //up right
buttons[x + 1][y - 1].setText(counts[x+1][y-1] + "");
buttons[x + 1][y - 1].setEnabled(false);
if (counts[x + 1][y - 1] == 0) {
toClear.add((x + 1)*100+(y - 1));
}
}
if(x > 0 && y > 0 && buttons[x-1][y].isEnabled()) { //left
buttons[x - 1][y].setText(counts[x-1][y] + "");
buttons[x - 1][y].setEnabled(false);
if (counts[x-1][y] == 0) {
toClear.add((x-1)*100+y);
}
}
if (x < counts.length - 1 && buttons[x+1][y].isEnabled()) { //right
buttons[x + 1][y].setText(counts[x+1][y] + "");
buttons[x + 1][y].setEnabled(false);
if (counts[x + 1][y] == 0) {
toClear.add((x + 1)*100+y);
}
}
if(x > 0 && y < counts[0].length - 1 && buttons[x-1][y+1].isEnabled()) { //down and left
buttons[x - 1][y + 1].setText(counts[x-1][y+1] + "");
buttons[x - 1][y + 1].setEnabled(false);
if (counts[x-1][y+1] == 0) {
toClear.add((x-1)*100+(y+1));
}
}
if (y < counts[0].length - 1 && buttons[x][y+1].isEnabled()) { // down
buttons[x][y + 1].setText(counts[x][y+1] + "");
buttons[x][y + 1].setEnabled(false);
if (counts[x][y + 1] == 0) {
toClear.add(x * 100+(y + 1));
}
}
if (x < counts.length - 1 && y < counts[0].length - 1 && buttons[x+1][y+1].isEnabled()) { //down right
buttons[x + 1][y + 1].setText(counts[x+1][y+1] + "");
buttons[x + 1][y + 1].setEnabled(false);
if (counts[x + 1][y + 1] == 0) {
toClear.add((x + 1)*100+(y + 1));
}
}
zeroCleaner(toClear);
}
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset)) {
//Resets the playing field
for (int x = 0; x < buttons.length; x++) {
for (int y = 0; y < buttons[0].length; y++) {
buttons[x][y].setEnabled(true);
buttons[x][y].setText("▒");
}
}
makeRandomMines();
}
else {
for (int x = 0; x < buttons.length ; x++) {
for (int y = 0; y < buttons[0].length; y++) {
if(event.getSource().equals(buttons[x][y])) {
if (counts[x][y]== MINE) {
lostGame();
}
else if(counts[x][y] == 0) {
buttons[x][y].setText(counts[x][y]+ "");
buttons[x][y].setEnabled(false);
ArrayList<Integer> toClear = new ArrayList<>();
toClear.add(x*100+y);
zeroCleaner(toClear);
checkWin();
}
else {
buttons[x][y].setText(counts[x][y]+ "");
buttons[x][y].setEnabled(false);
checkWin();
}
}
}
}
}
}
}
This should solve your problem:
for (int a = 0; a<buttons.length; a++) {
for (int b = 0; b < buttons[0].length; b++) {
buttons[a][b] = new JButton("▒");
buttons[a][b].addActionListener(this);
final int finalB = b;
final int finalA = a;
buttons[a][b].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
mineFlagger(true, finalA, finalB);
}
}
});
grid.add(buttons[a][b]);
}
}
public void mineFlagger (boolean flag, int x, int y){
buttons[x][y].setText("F");
}
Edit: for toggling the flag (lazy implementation)
if (SwingUtilities.isRightMouseButton(e)) {
mineFlagger(finalA, finalB);
}
public void mineFlagger(int x, int y) {
if(buttons[x][y].getText().equals("F")) {
buttons[x][y].setText("▒");
} else if (buttons[x][y].getText().equals("▒")){
buttons[x][y].setText("F");
}
}
If you import 'javax.swing.SwingUtilities' you could use utilities methods:
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
Then when a right mouse button is pressed, get the location of the mouse, find the button at that location, and then use that event to change the picture on that particular button to a picture of a flag.
You could use:
MouseInfo.getPointerInfo().getLocation()
To obtain the location of the mouse relative to the screen.

I can't seem to get a working main method for my project

I am programming a minesweeper game, and having a problem making the main method. I cant seem to get the text based game to output to the screen, allowing the user to interact with it. I have tried several ways, but none have worked.
public class Game {
private Board board;
boolean finish = false;
boolean win = false;
int turn = 0;
public void Jogo() {
board = new Board();
Play(board);
}
public void Play(Board board) {
do {
turn++;
System.out.println("Turn " + turn);
board.show();
finish = board.setPosition();
if (!finish) {
board.openNeighbors();
finish = board.win();
}
} while (!finish);
if (board.win()) {
System.out.println("Congratulations, you let the 10 fields with the mines in " + turn
+ " turns");
board.showMines();
} else {
System.out.println("Mine! You lost!");
board.showMines();
}
}
}
import java.util.Random;
import java.util.Scanner;
public class Board extends Game {
private int[][] mines;
private char[][] boardgame;
private int Line, Column;
Random random = new Random();
Scanner input = new Scanner(System.in);
public void Jogo() {
mines = new int[10][10];
boardgame = new char[10][10];
startMines();
randomMines();
fillTips();
startBoard();
}
public boolean win() {
int count = 0;
for (int line = 1; line < 9; line++)
for (int column = 1; column < 9; column++)
if (boardgame[line][column] == '_')
count++;
if (count == 10)
return true;
else
return false;
}
public void openNeighbors() {
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if ((mines[Line + i][Column + j] != -1)
&& (Line != 0 && Line != 9 && Column != 0 && Column != 9))
boardgame[Line + i][Column + j] =
Character.forDigit(mines[Line + i][Column + j], 10);
}
public int getPosition(int Line, int Column) {
return mines[Line][Column];
}
public boolean setPosition() {
do {
System.out.print("\nLine: ");
Line = input.nextInt();
System.out.print("Column: ");
Column = input.nextInt();
if ((boardgame[Line][Column] != '_')
&& ((Line < 9 && Line > 0) && (Column < 9 && Column > 0)))
System.out.println("Field already shown");
if (Line < 1 || Line > 8 || Column < 1 || Column > 8)
System.out.println("Choose a number between 1 and 8");
} while ((Line < 1 || Line > 8 || Column < 1 || Column > 8)
|| (boardgame[Line][Column] != '_'));
if (getPosition(Line, Column) == -1)
return true;
else
return false;
}
public void show() {
System.out.println("\n Lines");
for (int Line = 8; Line > 0; Line--) {
System.out.print(" " + Line + " ");
for (int Column = 1; Column < 9; Column++) {
System.out.print(" " + boardgame[Line][Column]);
}
System.out.println();
}
System.out.println("\n 1 2 3 4 5 6 7 8");
System.out.println(" Columns");
}
public void fillTips() {
for (int line = 1; line < 9; line++)
for (int column = 1; column < 9; column++) {
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
if (mines[line][column] != -1)
if (mines[line + i][column + j] == -1)
mines[line][column]++;
}
}
public void showMines() {
for (int i = 1; i < 9; i++)
for (int j = 1; j < 9; j++)
if (mines[i][j] == -1)
boardgame[i][j] = '*';
show();
}
public void startBoard() {
for (int i = 1; i < mines.length; i++)
for (int j = 1; j < mines.length; j++)
boardgame[i][j] = '_';
}
public void startMines() {
for (int i = 0; i < mines.length; i++)
for (int j = 0; j < mines.length; j++)
mines[i][j] = 0;
}
public void randomMines() {
boolean raffled;
int Line, Column;
for (int i = 0; i < 10; i++) {
do {
Line = random.nextInt(8) + 1;
Column = random.nextInt(8) + 1;
if (mines[Line][Column] == -1)
raffled = true;
else
raffled = false;
} while (raffled);
mines[Line][Column] = -1;
}
}
}
public class MineSweeper extends Board {
public static void main(String[] args) {
Game game = new Game();
}
}

How to make my game of life continue to the next generation?

Main Class
package edu.bsu.cs121.mamurphy;
public class GameOfLifeMain {
public static void main(String[] args) {
{
new GameOfLifeGUI();
System.out.println();
}
}
}
Tester Class
package edu.bsu.cs121.mamurphy;
import java.awt.Color;
import java.awt.Graphics;
import java.io.File;
import java.util.Scanner;
import javax.swing.JPanel;
public class tester extends JPanel
{
final static int ROW = 25, COL = 75;
final static char DOT = '.';
static char[][] grid = new char[ROW + 2][COL + 2];
static char[][] nextgrid = new char[ROW + 2][COL + 2];
boolean sameFlag;
boolean blankFlag;
public static void init(char[][] grid, char[][] nextgrid) {
for (int row = 0; row <= ROW + 1; row++) {
for (int col = 0; col <= COL + 1; col++) {
grid[row][col] = DOT;
nextgrid[row][col] = DOT;
}
}
}
public static void pause() {
try {
Thread.currentThread();
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
public void begin() {
init(grid, nextgrid);
read(grid);
repaint(); // calls paintComponent
pause();
while (sameFlag == true && blankFlag == false) {
nextGen(grid, nextgrid);
}
}
public static void read(char[][] grid) {
Scanner world = new Scanner(System.in);
System.out.println("Type the file name of the world you'd like to create.");
String fileName = world.nextLine();
{
try {
world = new Scanner(new File(fileName));
} catch (Exception ex) {
System.out.println("Please insert a valid file name.");
}
for (int row = 1; row <= ROW; row++) {
String s = world.next();
for (int col = 1; col <= COL; col++) {
grid[row][col] = s.charAt(col - 1);
}
}
}
}
public void print(Graphics g) {
int x, y;
y = 20;
for (int row = 1; row <= ROW; row++) {
x = 20;
for (int col = 1; col <= COL; col++) {
g.drawString("" + grid[row][col], x, y);
x = x + 7;
}
y = y + 15;
}
}
public static int neighbors(char[][] grid, int r, int c) {
// counts the # of closest neighbors that are X's
int count = 0;
for (int row = r - 1; row <= r + 1; row++) {
for (int col = c - 1; col <= c + 1; col++) {
if (grid[row][col] == 'X') {
count++;
}
}
}
if (grid[r][c] == 'X') {
count = count - 1;
}
return count;
}
public static void nextGen(char[][] grid, char[][] nextgrid) {
for (int row = 1; row <= ROW; row++) {
for (int col = 1; col <= COL; col++) {
if (grid[row][col] == 'X') {
int count = 0;
{
if (grid[row][col - 1] == 'X')
count = count + 1;
if (grid[row][col + 1] == 'X')
count = count + 1;
if (grid[row - 1][col] == 'X')
count = count + 1;
if (grid[row - 1][col - 1] == 'X')
count = count + 1;
if (grid[row - 1][col + 1] == 'X')
count = count + 1;
if (grid[row + 1][col - 1] == 'X')
count = count + 1;
if (grid[row + 1][col] == 'X')
count = count + 1;
if (grid[row + 1][col + 1] == 'X')
count = count + 1;
}
if (count == 2 || count == 3) {
nextgrid[row][col] = 'X';
} else
nextgrid[row][col] = DOT;
}
if (grid[row][col] == DOT) {
int count1 = 0;
{
if (grid[row][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row][col + 1] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row - 1][col + 1] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col - 1] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col] == 'X')
count1 = count1 + 1;
if (grid[row + 1][col + 1] == 'X')
count1 = count1 + 1;
}
if (count1 == 3)
nextgrid[row][col] = 'X';
}
}
}
}
public static void copy(char[][] grid, char[][] nextgrid) {
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
grid[i][j] = nextgrid[i][j];
}
}
}
public static boolean isEmpty(char[][] grid, char[][] nextgrid) {
boolean blankFlag = true;
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
if (grid[i][j] != DOT) {
blankFlag = false;
}
}
}
return blankFlag;
}
public static boolean isSame(char[][] grid, char[][] nextgrid) {
boolean sameFlag = false;
for (int i = 0; i < ROW + 1; i++) {
for (int j = 0; j < COL + 1; j++) {
if (grid[i][j] == nextgrid[i][j]) {
sameFlag = true;
break;
}
}
}
return sameFlag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);// erases panel Contents
g.setColor(Color.black);
if (sameFlag == false && blankFlag == false) {
print(g);
} else {
if (sameFlag == true) {
g.drawString("This worldis the same as the last one.", 10, 250);
}
if (blankFlag == true) {
g.drawString("Everyone died. Good job.", 10, 250);
}
}
}
}
GUI Class
package edu.bsu.cs121.mamurphy;
import javax.swing.*;
import java.awt.*;
//
public class GameOfLifeGUI extends JFrame {
public GameOfLifeGUI() {
super("Game of Life");
setSize(600, 445);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
tester test1 = new tester();
test1.setBackground(Color.LIGHT_GRAY);
panel.add(test1);
setContentPane(panel);
setVisible(true);
Temp one = new Temp(test1);
one.start();
}
class Temp extends Thread {
tester anim;
public Temp(tester anim) {
this.anim = anim;
}
public void run()// for each instance of test begin will be executed
{
anim.begin();
}
}
}
Hi stackoverflow. I have been working on this game of life project for the last few days and I have hit one final wall in trying to finish it up. How do I make it proceed to the next generation?
I know for what I am required to do I need to ask the user if they wish to continue to the next generation or not. I know I need to use a scanner and then have a loop that checks to see what the user's input is, as well as a try catch to make sure the program doesn't crash if they type in anything that isn't what the program asks them to.
My only issue is that I do not know where to put this code at in my tester class (if that is actually where it needs to go).
Any help is greatly appreciated.

Categories