Disable one JButton when another JBUtton is enabled - java

I'm trying to build a simple rolling dice game for my assignment. There will be 2 players. In my code I try to use method getSource() so that when a player roll JButton is enabled, the other player's button will be disabled but when I run the game both player's buttons are still enabled. Here are my code:
Die.java
import java.util.*;
public class Die
{
private final int MAX = 6;
private int die1;
Random rand = new Random();
//Constructor
public Die()
{
die1 = 1;
}// end Constructor
public int Roll()
{
die1 = rand.nextInt(MAX)+1;
return die1;
}
}
DisplaySixNumbersPanel.java
import java.awt.*;
import javax.swing.*;
public class DisplaySixNumbersPanel
{
public static void main(String[ ] args)
{
JFrame w1 = new JFrame("Six Numbers Game");
w1.setLayout(new GridLayout(1,2));
SixNumbersPanel2 player1 =new SixNumbersPanel2();
SixNumbersPanel2 player2 =new SixNumbersPanel2();
w1.add(player1);
w1.add(player2);
w1.setSize(540, 350);
w1.setVisible(true);
w1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} //end main
} //end class
SixNumbersPanel2.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class SixNumbersPanel2 extends JPanel implements ActionListener
{
private JTextField text1;
private boolean flag = false;
private boolean checkflag[] = {false,false,false,false,false,false,false};
private JLabel label;
private JLabel label1;
public JButton roll;
private JButton restartButton;
private JTextArea display;
private JTextField[] fields = new JTextField[7];
private Die dice = new Die();
private int key;
private int count;
private int count1;
private Player player1 = new Player();
private Player player2 = new Player();
private int check;
private int[] list = new int [7];
//private SixNumbersPanel2 player2panel;
public SixNumbersPanel2()
{
label= new JLabel ("A number between 1 to 6 wil appear");
label1 = new JLabel("once in each of the following textfields");
roll = new JButton("Roll dice");
restartButton = new JButton("Restart Game");
text1 = new JTextField(3);
display = new JTextArea(10,15);
add(label);
add(label1);
for(int i=1;i<7;i++)
{
fields[i] = new JTextField(3);
add(fields[i]);
}
add(roll);
add(text1);
add(display);
display.setEditable(false);
restartButton.setVisible(false);
add(restartButton);
restartButton.addActionListener(this);
roll.addActionListener(this);
}
public void restart()
{
display.setText("");
text1.setText("");
for(int i=1; i<7; i++)
{
fields[i].setText("");
}
count=0;
count1=0;
Arrays.fill(checkflag,false);
Arrays.fill(list,0);
flag = false;
restartButton.setVisible(false);
rollenable();
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == roll)
{
player2.rolldisable();
}
key=dice.Roll();
count++;
String toScreen= "Number of rolls: "+count;
display.setText(toScreen);
text1.setText(""+key);
check = player1.Check(list,key);
if(check < 0)
{
count1++;
for(int i=1;i<7;i++)
{
if(key == i)
{
list[i] = key;
checkflag[i]=true;
fields[i].setText(""+key);
if(checkflag[i] == true)
{
flag = true;
for(int a=1; a<7; a++)
{
if(checkflag[a]==false)
{
flag=false;
}
}
}
}
if(flag == true)
{
display.setText("Congratulation, you have \ntaken "+count+" rolls to get one of \neach number between 1 and 6");
rolldisable();
restartButton.setVisible(true);
}
}
}
if(event.getSource() == restartButton)
{
restart();
}
}
public void rollenable()
{
roll.setEnabled(true);
}
public void rolldisable()
{
roll.setEnabled(false);
}
public JButton getSubButton()
{
return this.roll;
}
}
Player.java
import java.util.*;
import javax.swing.*;
public class Player
{
private final int MAX = 100;
private Die play = new Die();
private boolean[] results = {false,false,false,false,false,false,false};
private int count;
private int key;
private boolean check = false;
//private JButton roll;
public Player()
{
count=0;
key=0;
}
public void Play()
{
for(int i=0;i<MAX;i++)
{
key=play.Roll();
System.out.print("\nNumber rolled: "+key);
count++;
for(int a=1;a<7;a++)
{
if(a==key)
{
results[a]=true;
System.out.print("\nSo far, you have rolled ");
if(results[a]==true)
{
check=true;
for(int k=1;k<7;k++)
{
if(results[k] ==true)
{
System.out.print(" "+k+" ");
}
if(results[k] == false)
check=false;
}
}
}
}
if(check==true)
{
System.out.print("\nCongratulations, you have taken "+count+" rolls to get one of each number between 1 and 6");
break;
}
}
}
public int Check(int []check,int key)
{
int check1= Arrays.binarySearch(check,key);
return check1;
}
//public JButton getButton()
//{
// JButton button = null;
//SixNumbersPanel2 roll = new SixNumbersPanel2();
//return roll.roll = button;
//}
public void rolldisable()
{
SixNumbersPanel2 dis = new SixNumbersPanel2();
dis.getSubButton().setEnabled(false);
}
}
Also with the restartButton JButton, it doesn't restart the whole game but only for the player who clicks it. Any suggestion as how to make it restart the whole GUI would be awesome.
All helps would be appreciated.

This...
public void rolldisable()
{
SixNumbersPanel2 dis = new SixNumbersPanel2();
dis.getSubButton().setEnabled(false);
}
is wrong, basically you're creating a new instance of SixNumbersPanel2 and are trying to change it's state, but it's not actually displayed on the screen nor does it have anything to do with what is displayed on the screen.
This solution is not a simple one. What you need is some kind of model/controller which can be shared between the two instances of SixNumbersPanel2 and which generate appropriate state events to which they can respond.
You will need to devise some way of identifying which player is which so each SixNumbersPanel2 knows which player it represents and which player is currently active
Updated...
In order to implement the function changes needed, you need some kind of "central" hub, which is managing the core functionality and which can generate notification/events when the state changes in some meaningful way (like the next players turn)
In broad terms, these are covered by:
Model-View-Controller
Observer Patten
First, we need to start with some kind of token, to differentiate the players...
enum Player {
ONE, TWO;
}
Next, we need some kind of "model", which is used to manage the data and the core functionality
public interface SixNumbersModel {
public Player getCurrentTurn();
public Player nextTurn();
public int roll();
public boolean hasWon(Player player);
public Set<Integer> getPlayerResults(Player player);
public int getTurnsCount(Player player);
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
}
nb: You could actually have a "player model" which managed the results, but I'm been lazy
The reason I've started with a interface is users of the model should not care about how the model is implemented (implementations might seperate the management of each players results into individual models, but users of the SixNumbersModel won't care)
public class DefaultSizeNumbersModel implements SixNumbersModel {
private List<ChangeListener> changeListeners;
private Die die = new Die();
private Player turn;
private Map<Player, Set<Integer>> results;
private Map<Player, Integer> turns;
public DefaultSizeNumbersModel() {
changeListeners = new ArrayList<>(2);
results = new HashMap<>();
results.put(Player.ONE, new HashSet<>(6));
results.put(Player.TWO, new HashSet<>(6));
turns = new HashMap<>(2);
turns.put(Player.ONE, 0);
turns.put(Player.TWO, 0);
setCurrentTurn(Player.ONE);
}
#Override
public Player getCurrentTurn() {
return turn;
}
protected void setCurrentTurn(Player player) {
turn = player;
}
#Override
public Player nextTurn() {
switch (getCurrentTurn()) {
case ONE:
setCurrentTurn(Player.TWO);
break;
case TWO:
setCurrentTurn(Player.ONE);
break;
default:
setCurrentTurn(Player.ONE);
break;
}
fireStateChanged();
return getCurrentTurn();
}
#Override
public int roll() {
incrementTurnCount(getCurrentTurn());
int result = die.Roll();
Set<Integer> playerResults = results.get(getCurrentTurn());
playerResults.add(result);
return result;
}
#Override
public boolean hasWon(Player player) {
Set<Integer> playerResults = results.get(getCurrentTurn());
return playerResults.size() == 5; // 0...5
}
#Override
public Set<Integer> getPlayerResults(Player player) {
Set<Integer> actualResults = results.get(player);
Set<Integer> copy = new HashSet<>(actualResults);
return copy;
}
#Override
public int getTurnsCount(Player player) {
return turns.get(player);
}
protected void setTurnsCount(Player player, int count) {
turns.put(player, count);
}
protected void incrementTurnCount(Player player) {
int count = getTurnsCount(player);
count++;
setTurnsCount(player, count);
}
#Override
public void addChangeListener(ChangeListener listener) {
changeListeners.add(listener);
}
#Override
public void removeChangeListener(ChangeListener listener) {
changeListeners.remove(listener);
}
protected void fireStateChanged() {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : changeListeners) {
listener.stateChanged(evt);
}
}
}
Then we need some kind of "view"...
public class SixNumbersPanel extends JPanel {
private Player player;
private SixNumbersModel model;
private JButton roll;
private JTextArea ta;
public SixNumbersPanel(Player player, SixNumbersModel model) {
this.player = player;
this.model = model;
model.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
roll.setEnabled(player == model.getCurrentTurn());
}
});
roll = new JButton("Roll");
ta = new JTextArea(5, 10);
roll.setEnabled(player == model.getCurrentTurn());
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel(player.name()), gbc);
add(roll, gbc);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(ta), gbc);
roll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int result = model.roll();
ta.append(Integer.toString(result) + "\n");
if (model.hasWon(player)) {
JOptionPane.showMessageDialog(SixNumbersPanel.this, player + " has won");
}
model.nextTurn();
}
});
}
}
Okay, massively basic, but, it simply has a button and a text area. It registers interest to the model to be notified when the state changes and makes sure that the button is only enabled when the player it represents is the current player.
Runnable example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Test {
public static void main(String[] args) {
new Test();
}
enum Player {
ONE, TWO;
}
public interface SixNumbersModel {
public Player getCurrentTurn();
public Player nextTurn();
public int roll();
public boolean hasWon(Player player);
public Set<Integer> getPlayerResults(Player player);
public int getTurnsCount(Player player);
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
}
public class DefaultSizeNumbersModel implements SixNumbersModel {
private List<ChangeListener> changeListeners;
private Die die = new Die();
private Player turn;
private Map<Player, Set<Integer>> results;
private Map<Player, Integer> turns;
public DefaultSizeNumbersModel() {
changeListeners = new ArrayList<>(2);
results = new HashMap<>();
results.put(Player.ONE, new HashSet<>(6));
results.put(Player.TWO, new HashSet<>(6));
turns = new HashMap<>(2);
turns.put(Player.ONE, 0);
turns.put(Player.TWO, 0);
setCurrentTurn(Player.ONE);
}
#Override
public Player getCurrentTurn() {
return turn;
}
protected void setCurrentTurn(Player player) {
turn = player;
}
#Override
public Player nextTurn() {
switch (getCurrentTurn()) {
case ONE:
setCurrentTurn(Player.TWO);
break;
case TWO:
setCurrentTurn(Player.ONE);
break;
default:
setCurrentTurn(Player.ONE);
break;
}
fireStateChanged();
return getCurrentTurn();
}
#Override
public int roll() {
incrementTurnCount(getCurrentTurn());
int result = die.Roll();
Set<Integer> playerResults = results.get(getCurrentTurn());
playerResults.add(result);
return result;
}
#Override
public boolean hasWon(Player player) {
Set<Integer> playerResults = results.get(getCurrentTurn());
return playerResults.size() == 5; // 0...5
}
#Override
public Set<Integer> getPlayerResults(Player player) {
Set<Integer> actualResults = results.get(player);
Set<Integer> copy = new HashSet<>(actualResults);
return copy;
}
#Override
public int getTurnsCount(Player player) {
return turns.get(player);
}
protected void setTurnsCount(Player player, int count) {
turns.put(player, count);
}
protected void incrementTurnCount(Player player) {
int count = getTurnsCount(player);
count++;
setTurnsCount(player, count);
}
#Override
public void addChangeListener(ChangeListener listener) {
changeListeners.add(listener);
}
#Override
public void removeChangeListener(ChangeListener listener) {
changeListeners.remove(listener);
}
protected void fireStateChanged() {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : changeListeners) {
listener.stateChanged(evt);
}
}
}
public class Die {
private final int MAX = 6;
private int die1;
Random rand = new Random();
//Constructor
public Die() {
die1 = 1;
}// end Constructor
public int Roll() {
die1 = rand.nextInt(MAX) + 1;
return die1;
}
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Roll Six");
frame.setLayout(new GridLayout(2, 0));
SixNumbersModel model = new DefaultSizeNumbersModel();
SixNumbersPanel onePane = new SixNumbersPanel(Player.ONE, model);
SixNumbersPanel twoPane = new SixNumbersPanel(Player.TWO, model);
frame.add(onePane);
frame.add(twoPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SixNumbersPanel extends JPanel {
private Player player;
private SixNumbersModel model;
private JButton roll;
private JTextArea ta;
public SixNumbersPanel(Player player, SixNumbersModel model) {
this.player = player;
this.model = model;
model.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
roll.setEnabled(player == model.getCurrentTurn());
}
});
roll = new JButton("Roll");
ta = new JTextArea(5, 10);
roll.setEnabled(player == model.getCurrentTurn());
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel(player.name()), gbc);
add(roll, gbc);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(ta), gbc);
roll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int result = model.roll();
ta.append(Integer.toString(result) + "\n");
if (model.hasWon(player)) {
JOptionPane.showMessageDialog(SixNumbersPanel.this, player + " has won");
}
model.nextTurn();
}
});
}
}
}

Related

How to have the program regenerate a "new game" where previous grid letters get swapped with new grid letters

In this program I'm trying to input a functionality to start game, where if I click start game (MainMenu) a new jpanel opens up (MainGame), creating another jpanel that creates jbuttons in a grid. If i go back, and click start game again, a new grid should generate instead of the previous one, effectively starting a "new game". the problem is that if i go back and click on new game again, the program creates 2 grids.
I've tried removing the instance of the grid panel with = null but it doesn't work
Main function:
import javax.swing.*;
import java.awt.*;
import java.awt.CardLayout;
public class Game extends JFrame {
MainMenu mainMenu;
Settings settings;
MainGame mainGame;
CardLayout cl;
JPanel container;
public Game(){
setSize(900,900); //have all as seperate classes
setDefaultCloseOperation(3); //cl call container
container = new JPanel(); //container call menu1 and menu2
cl = new CardLayout();
mainMenu = new MainMenu();
settings = new Settings();
mainGame = new MainGame();
mainMenu.setSettings(settings);
settings.setMainMenu(mainMenu);
settings.setMainGame(mainGame);
mainMenu.setMainGame(mainGame);
mainGame.setMainMenu(mainMenu);
mainGame.setSettings(settings);
container.setLayout(cl); //this stays here i think
//add setter for main game here
container.add(mainMenu,"1");
container.add(settings,"2");
container.add(mainGame,"3");
mainMenu.setContainer(container);
mainMenu.setCl(cl);
settings.setContainer(container);
settings.setCl(cl);
mainGame.setContainer(container);
mainGame.setCl(cl);
cl.show(container, "1");
add(container,BorderLayout.CENTER);
}
public static void main(String[] args) {
Game game = new Game();
game.setVisible(true);
}
}
main game class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainGame extends JPanel {
MainMenu mainMenu;
Settings settings;
CardLayout cl;
JPanel container;
String rows;
String columns;
public void setMainMenu(MainMenu mainMenu) {
this.mainMenu = mainMenu;
}
public void setSettings(Settings settings) {
this.settings = settings;
}
public void setCl(CardLayout cl) {
this.cl = cl;
}
public void setContainer(JPanel container) {
this.container = container;
}
public void setRows(String rows) {
this.rows = rows;
}
public void setColumns(String columns) {
this.columns = columns;
}
public MainGame(){
JPanel north = new JPanel();
north.setLayout(new FlowLayout());
ReturnAction returnAl = new ReturnAction();
JButton Return2 = new JButton("Return");
Return2.addActionListener(returnAl);
north.add(Return2);
add(north);
}
class ReturnAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(container,"1");
}
}
}
Main menu class (this one contains the game generation part):
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MainMenu extends JPanel {
JPanel grid = new JPanel();
MainGame mainGame;
Settings settings;
CardLayout cl;
JPanel container;
String rows;
String columns;
boolean checkexists = false;
int rownumber;
int columnnumber;
public void setMainGame(MainGame mainGame) {
this.mainGame = mainGame;
}
public void setCl(CardLayout cl) {
this.cl = cl;
}
public void setContainer(JPanel container) {
this.container = container;
}
public void setSettings(Settings settings) {
this.settings = settings;
}
public void setRows(String rows) {
this.rows = rows;
}
public void setColumns(String columns) {
this.columns = columns;
}
public MainMenu() {
setLayout(new GridLayout(3, 1));
JButton Newgame = new JButton("New Game");
JButton Cont = new JButton("Continue");
JButton Sett = new JButton("Settings");
add(Newgame);
add(Cont);
SwitchMenu1 switchMenu1 = new SwitchMenu1();
SwitchMenu2 switchMenu2 = new SwitchMenu2();
GenerateGame generateGame = new GenerateGame();
Newgame.addActionListener(switchMenu2);
Newgame.addActionListener(generateGame);
Sett.addActionListener(switchMenu1);
add(Sett);
}
class SwitchMenu1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(container, "2");
}
}
class SwitchMenu2 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(container, "3");
}
}
class GenerateGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (checkexists == true){
grid = null;
grid = new JPanel();
}
try {
rownumber = Integer.parseInt(rows);
} catch (NumberFormatException be) {
rownumber = 10;
}
try {
columnnumber = Integer.parseInt(columns);
} catch (NumberFormatException be) {
columnnumber = 10;
}
Random rand = new Random();
int randomnumber;
String Letters = "AAIIOOUUEEABCDEFGHIJKLMNOPQRSTUVWXYZ";
grid.setLayout(new GridLayout(rownumber, columnnumber));
JButton[][] gridbutton = new JButton[rownumber][columnnumber];
MainbuttonAL mainbuttonAL = new MainbuttonAL();
for (int i = 0; i < rownumber; i++) {
for (int j = 0; j < columnnumber; j++) {
if (checkexists == true){
gridbutton[i][j] = null;
}
randomnumber = rand.nextInt(Letters.length());
gridbutton[i][j] = new JButton("" + Letters.charAt(randomnumber));
gridbutton[i][j].addActionListener(mainbuttonAL);
grid.add(gridbutton[i][j]);
}
}
mainGame.add(grid);
checkexists = true;
}
}
class MainbuttonAL implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
}
}
}
settings class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MainMenu extends JPanel {
JPanel grid = new JPanel();
MainGame mainGame;
Settings settings;
CardLayout cl;
JPanel container;
String rows;
String columns;
boolean checkexists = false;
int rownumber;
int columnnumber;
public void setMainGame(MainGame mainGame) {
this.mainGame = mainGame;
}
public void setCl(CardLayout cl) {
this.cl = cl;
}
public void setContainer(JPanel container) {
this.container = container;
}
public void setSettings(Settings settings) {
this.settings = settings;
}
public void setRows(String rows) {
this.rows = rows;
}
public void setColumns(String columns) {
this.columns = columns;
}
public MainMenu() {
setLayout(new GridLayout(3, 1));
JButton Newgame = new JButton("New Game");
JButton Cont = new JButton("Continue");
JButton Sett = new JButton("Settings");
add(Newgame);
add(Cont);
SwitchMenu1 switchMenu1 = new SwitchMenu1();
SwitchMenu2 switchMenu2 = new SwitchMenu2();
GenerateGame generateGame = new GenerateGame();
Newgame.addActionListener(switchMenu2);
Newgame.addActionListener(generateGame);
Sett.addActionListener(switchMenu1);
add(Sett);
}
class SwitchMenu1 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(container, "2");
}
}
class SwitchMenu2 implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(container, "3");
}
}
class GenerateGame implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (checkexists == true){
grid = null;
grid = new JPanel();
}
try {
rownumber = Integer.parseInt(rows);
} catch (NumberFormatException be) {
rownumber = 10;
}
try {
columnnumber = Integer.parseInt(columns);
} catch (NumberFormatException be) {
columnnumber = 10;
}
Random rand = new Random();
int randomnumber;
String Letters = "AAIIOOUUEEABCDEFGHIJKLMNOPQRSTUVWXYZ";
grid.setLayout(new GridLayout(rownumber, columnnumber));
JButton[][] gridbutton = new JButton[rownumber][columnnumber];
MainbuttonAL mainbuttonAL = new MainbuttonAL();
for (int i = 0; i < rownumber; i++) {
for (int j = 0; j < columnnumber; j++) {
if (checkexists == true){
gridbutton[i][j] = null;
}
randomnumber = rand.nextInt(Letters.length());
gridbutton[i][j] = new JButton("" + Letters.charAt(randomnumber));
gridbutton[i][j].addActionListener(mainbuttonAL);
grid.add(gridbutton[i][j]);
}
}
mainGame.add(grid);
checkexists = true;
}
}
class MainbuttonAL implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
}
}
}
what method can i employ to regenerate a grid?
In general, you should be working on the concept of decoupling your views and your data, this means that you could have a "game model" which could be applied to a view and the view would then modify itself based on model properties, this is commonly known as "model - view - controller".
The problem is, however, you never remove grid from it's parent container when you create a new game
if (checkexists == true){
grid = null;
grid = new JPanel();
}
Instead, before you re-intialise the grid, you should remove from it's parent container
if (grid != null) {
mainGame.remove(grid);
grid = null;
grid = new JPanel();
}
or you could just remove the components from the grid panel itself
grid.removeAll();
A different approach...
At all stages you should be trying to decouple you objects and workflows from each other, so that it's easier to change any one part without having adverse effects on the other parts of the system or workflow.
Looking at you code, for example, the navigation decisions are tightly coupled to each panel/view, but in reality, they shouldn't know or care about how the navigation works (or the fact that there are other views), they should just do there job.
You can decouple this workflow through the use of delegation (backed by an observer). This basically means that the individual view doesn't care "how" the navigation works, only that when it makes a request for some action to be taken, it happens.
You should take the time to read through...
Model-View-Controller
Observer Pattern
Dependency Injection in Java
But how does this help you? Well, it will help you all the time!
Lets start with the "game" itself. The first thing we need is some kind of container to hold the data base logic for the game, so based on your current code, it might look something like...
public interface GameModel {
public int getRows();
public int getColumns();
}
I know, amazing isn't it, but this interface would grow to hold the logic required to run your game.
Now, we can apply this to the GamePanel
public class GamePane extends JPanel {
public interface Obsever {
public void back(GamePane source);
}
private GameModel model;
private Obsever obsever;
private JPanel contentPane;
private ActionListener buttonActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
didTap(e.getActionCommand());
}
};
public GamePane(Obsever obsever) {
this.obsever = obsever;
setLayout(new BorderLayout());
contentPane = new JPanel();
add(new JScrollPane(contentPane));
JButton backButton = new JButton("<< Back");
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
obsever.back(GamePane.this);
}
});
JPanel bannerPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.LINE_END;
bannerPane.add(backButton, gbc);
add(bannerPane, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
// Bunch of things we could do here, but this basically
// acts as a stand in for CardLayout, otherwise the primary
// view will be to small
return new Dimension(800, 800);
}
public void setModel(GameModel model) {
if (this.model == model) {
// Do nothing, nothings changed
return;
}
this.model = model;
buildUI();
}
protected void buildUI() {
contentPane.removeAll();
if (model == null) {
return;
}
String Letters = "AAIIOOUUEEABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
JButton[][] gridbutton = new JButton[model.getRows()][model.getColumns()];
contentPane.setLayout(new GridLayout(model.getRows(), model.getColumns()));
//Game.MainMenu.MainbuttonAL mainbuttonAL = new Game.MainMenu.MainbuttonAL();
for (int i = 0; i < model.getRows(); i++) {
for (int j = 0; j < model.getColumns(); j++) {
int randomnumber = rnd.nextInt(Letters.length());
gridbutton[i][j] = new JButton("" + Letters.charAt(randomnumber));
//gridbutton[i][j].addActionListener(mainbuttonAL);
contentPane.add(gridbutton[i][j]);
}
}
}
protected void didTap(String action) {
}
}
Now, the nice "juicy" part is in the buildUI which is called by setModel when the model changes. This just re-builds the UI based on the GameModel properties.
As for the navigation concept, you can see part of it in the GamePane via its Observer interface. I started by creating a seperate class to handle the navigation workflows.
This means that the "how" or "implementation detail" is decoupled or hidden from the other parts of the system. Instead, it makes use of simple observer/delegation workflow.
Each view provides an Observer (for the what of a better name) which describes the navigation actions it needs performed. For example, both the SettingsPane and GamePane simply have back. They don't care what came before them, that's up to the navigation controller to decide.
public class NavigationPane extends JPanel {
enum View {
MAIN_MENU, GAME, SETTINGS
}
private CardLayout cardLayout;
private GameModel model;
private GamePane gamePane;
// Just for testing...
private Random rnd = new Random();
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
add(new MainMenu(new MainMenu.Observer() {
#Override
public void newGame(MainMenu source) {
gamePane.setModel(createModel());
navigateTo(View.GAME);
}
#Override
public void continueGame(MainMenu source) {
// Because it's possible to push continue
// without starting a game
// It might be possible have a "menu" model
// which can be used to change the enabled state of
// the continue button based on the state of the
// game
gamePane.setModel(getOrCreateGameModel());
navigateTo(View.GAME);
}
#Override
public void settingsGame(MainMenu source) {
navigateTo(View.SETTINGS);
}
}), View.MAIN_MENU);
gamePane = new GamePane(new GamePane.Obsever() {
#Override
public void back(GamePane source) {
navigateTo(View.MAIN_MENU);
}
});
add(gamePane, View.GAME);
add(new SettingsPane(new SettingsPane.Obsever() {
#Override
public void back(SettingsPane source) {
navigateTo(View.MAIN_MENU);
}
}), View.SETTINGS);
navigateTo(View.MAIN_MENU);
}
protected GameModel createModel() {
model = new DefaultGameModel(rnd.nextInt(9) + 2, rnd.nextInt(9) + 2);
return model;
}
protected GameModel getOrCreateGameModel() {
if (model == null) {
model = createModel();
}
return model;
}
protected void add(Component component, View view) {
add(component, view.name());
}
protected void navigateTo(View view) {
cardLayout.show(this, view.name());
}
}
Runnable example...
So, that's a lot of out-of-context code. The below is basically an example of one possible approach you could take to further reduce some of the clutter and coupling which is growing in your code base at this time.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new NavigationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class NavigationPane extends JPanel {
enum View {
MAIN_MENU, GAME, SETTINGS
}
private CardLayout cardLayout;
private GameModel model;
private GamePane gamePane;
// Just for testing...
private Random rnd = new Random();
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
add(new MainMenu(new MainMenu.Observer() {
#Override
public void newGame(MainMenu source) {
gamePane.setModel(createModel());
navigateTo(View.GAME);
}
#Override
public void continueGame(MainMenu source) {
// Because it's possible to push continue
// without starting a game
// It might be possible have a "menu" model
// which can be used to change the enabled state of
// the continue button based on the state of the
// game
gamePane.setModel(getOrCreateGameModel());
navigateTo(View.GAME);
}
#Override
public void settingsGame(MainMenu source) {
navigateTo(View.SETTINGS);
}
}), View.MAIN_MENU);
gamePane = new GamePane(new GamePane.Obsever() {
#Override
public void back(GamePane source) {
navigateTo(View.MAIN_MENU);
}
});
add(gamePane, View.GAME);
add(new SettingsPane(new SettingsPane.Obsever() {
#Override
public void back(SettingsPane source) {
navigateTo(View.MAIN_MENU);
}
}), View.SETTINGS);
navigateTo(View.MAIN_MENU);
}
protected GameModel createModel() {
model = new DefaultGameModel(rnd.nextInt(9) + 2, rnd.nextInt(9) + 2);
return model;
}
protected GameModel getOrCreateGameModel() {
if (model == null) {
model = createModel();
}
return model;
}
protected void add(Component component, View view) {
add(component, view.name());
}
protected void navigateTo(View view) {
cardLayout.show(this, view.name());
}
}
public class MainMenu extends JPanel {
public interface Observer {
public void newGame(MainMenu source);
public void continueGame(MainMenu source);
public void settingsGame(MainMenu source);
}
private Observer observer;
public MainMenu(Observer observer) {
this.observer = observer;
setLayout(new GridBagLayout());
JButton newGameButton = new JButton("New Game");
JButton continueButton = new JButton("Continue");
JButton settingsButton = new JButton("Settings");
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(newGameButton, gbc);
add(continueButton, gbc);
add(settingsButton, gbc);
newGameButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.newGame(MainMenu.this);
}
});
continueButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.continueGame(MainMenu.this);
}
});
settingsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.settingsGame(MainMenu.this);
}
});
}
}
public class SettingsPane extends JPanel {
public interface Obsever {
public void back(SettingsPane source);
}
public SettingsPane(Obsever obsever) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new JLabel("All your setting belong to us"), gbc);
JButton backButton = new JButton("<< Back");
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
obsever.back(SettingsPane.this);
}
});
add(backButton, gbc);
}
}
public interface GameModel {
public int getRows();
public int getColumns();
}
public class DefaultGameModel implements GameModel {
private int rows;
private int columns;
public DefaultGameModel(int rows, int columns) {
this.rows = rows;
this.columns = columns;
}
#Override
public int getRows() {
return rows;
}
#Override
public int getColumns() {
return columns;
}
}
public class GamePane extends JPanel {
public interface Obsever {
public void back(GamePane source);
}
private GameModel model;
private Obsever obsever;
private JPanel contentPane;
private ActionListener buttonActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
didTap(e.getActionCommand());
}
};
public GamePane(Obsever obsever) {
this.obsever = obsever;
setLayout(new BorderLayout());
contentPane = new JPanel();
add(new JScrollPane(contentPane));
JButton backButton = new JButton("<< Back");
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
obsever.back(GamePane.this);
}
});
JPanel bannerPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.LINE_END;
bannerPane.add(backButton, gbc);
add(bannerPane, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
// Bunch of things we could do here, but this basically
// acts as a stand in for CardLayout, otherwise the primary
// view will be to small
return new Dimension(800, 800);
}
public void setModel(GameModel model) {
if (this.model == model) {
// Do nothing, nothings changed
return;
}
this.model = model;
buildUI();
}
protected void buildUI() {
contentPane.removeAll();
if (model == null) {
return;
}
String Letters = "AAIIOOUUEEABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
JButton[][] gridbutton = new JButton[model.getRows()][model.getColumns()];
contentPane.setLayout(new GridLayout(model.getRows(), model.getColumns()));
//Game.MainMenu.MainbuttonAL mainbuttonAL = new Game.MainMenu.MainbuttonAL();
for (int i = 0; i < model.getRows(); i++) {
for (int j = 0; j < model.getColumns(); j++) {
int randomnumber = rnd.nextInt(Letters.length());
gridbutton[i][j] = new JButton("" + Letters.charAt(randomnumber));
//gridbutton[i][j].addActionListener(mainbuttonAL);
contentPane.add(gridbutton[i][j]);
}
}
}
protected void didTap(String action) {
}
}
}

Listeners wouldn't work when a serialized panel is deserialized and retrieved (Java)

I'm designing a JPanel in which there are some buttons which have their own action listeners and would do certain things when clicked (for example, one of them would remove the panel). In case the user closes the program, panels shouldn't be deleted and should be retrieved. for this purpose I serialize panels and deserialize them when needed. but the problem is listeners such as action listeners and mouse listeners wouldn't work when the panel is retrieved. is there any way to solve this problem? or is there any alternative to do the same thing without problem?
My panel code in case it's needed:
import jdk.internal.org.objectweb.asm.commons.SerialVersionUIDAdder;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.text.Format;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Random;
public class Download extends JPanel implements Serializable {
private String fileName;
private boolean removed = false;
private double downloadSpeed;
private double downloadedSize;
private double sizeOfFile;
LocalTime downloadTime;
LocalDate downloadDate;
private boolean checked = false;
private static final long serialVersionUID = 1113799434508676095L;
JLabel test = new JLabel("test");
public Download (MainPage c,URL url,LocalTime time,LocalDate date) {
setLayout(null);
downloadDate = date;
downloadTime = time;
fileName = url.getFile();
JCheckBox checkbox = new JCheckBox();
checkbox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
setChecked(true);
else
setChecked(false);
}
});
checkbox.setBackground(new Color(186,212,215));
checkbox.setBounds(95,42,17,15);
add(checkbox);
MouseAdapter a = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
setBackground(new Color(224,235,252));
checkbox.setBackground(new Color(224,235,252));
}
#Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
setBackground(new Color(186,212,255));
checkbox.setBackground(new Color(186,212,255));
}
};
UIManager.put("ProgressBar.background", new Color (235,255,255));
UIManager.put("ProgressBar.foreground", new Color (10,109,63));
UIManager.put("ProgressBar.selectionBackground", Color.RED);
UIManager.put("ProgressBar.selectionForeground", Color.GREEN);
setBackground(new Color(186,212,255));
setPreferredSize(new Dimension(600,100));
JPanel file = new JPanel();
/* test fileImg = new test("file.png");
fileImg.setBounds(10,10,40,50);
add(fileImg); */
JLabel fileNameLabel = new JLabel(fileName);
fileNameLabel.setBounds(100,5,400,15);
fileNameLabel.setForeground(new Color(109,111,114));
add(fileNameLabel);
JProgressBar jpb = new JProgressBar(0,100);
Random r = new Random();
jpb.setValue(r.nextInt(100));
jpb.setBounds(100,25,400,10);
JLabel progressBarValue = new JLabel("%" + jpb.getValue() + "");
progressBarValue.setBounds(510,18,25,20);
add(progressBarValue);
this.setBorder(BorderFactory.createMatteBorder(0,0,2,0,new Color(18,42,79)));
addMouseListener(a);
add(jpb);
JButton trash = new JButton(new ImageIcon("trash.png"));
trash.setBounds(130,40,25,25);
/* trash.setContentAreaFilled(false);
trash.setFocusPainted (false);
trash.setBorderPainted(false); */
trash.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("text");
}
});
add(trash);
test.setBounds(180,40,25,25);
test.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
System.out.println("text");
}
});
add(test);
double lower = 0;
double upper = 999.99;
sizeOfFile = Math.random() * (upper - lower) + lower;
downloadSpeed = Math.random() * (upper - lower) + lower;
downloadedSize = jpb.getValue() * sizeOfFile / 100;
JLabel downloadSpeedLabel = new JLabel (String.format ("%.1fKbs",downloadSpeed));
JLabel downloadedSizeLabel = new JLabel (String.format ("%.1fMG / %.2fMG",downloadedSize,sizeOfFile));
downloadedSizeLabel.setForeground(new Color(109,111,114));
downloadSpeedLabel.setForeground(new Color(109,111,114));
downloadSpeedLabel.setBounds(250,35,100,30);
downloadedSizeLabel.setBounds(420,35,150,30);
add(downloadSpeedLabel); add(downloadedSizeLabel);
}
public boolean isRemoved() {
return removed;
}
public void setRemoved(boolean removed) {
this.removed = removed;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public double getDownloadSpeed() {
return downloadSpeed;
}
public void setDownloadSpeed(double downloadSpeed) {
this.downloadSpeed = downloadSpeed;
}
public double getDownloadedSize() {
return downloadedSize;
}
public void setDownloadedSize(double downloadedSize) {
this.downloadedSize = downloadedSize;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public double getSizeOfFile() {
return sizeOfFile;
}
public void setSizeOfFile(double size) {
this.sizeOfFile = size;
}
}

JPanel doesn't react to MouseEvents?

I'm trying to create a "Tic Tac Toe" game. I've chosen to create a variation of JPanel to represent each square. The class beneath represents one of 9 panels that together make up my game board.
Now the problem I'm having is that when I click the panel a 'X' should be displayed inside of the panel, but nothing happens. I'd very much appreciate it if someone steered me in the right direction.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToePanel extends JPanel implements MouseListener {
private boolean isPlayer1Turn = true;
private boolean isUsed = false;
private JLabel ticTacLbl = new JLabel();
public TicTacToePanel() {
setBorder(BorderFactory.createLineBorder(Color.BLACK));
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
if (!isUsed) {
if (isPlayer1Turn) {
ticTacLbl.setForeground(Color.red);
ticTacLbl.setText("X");
add(ticTacLbl, 0);
isUsed = true;
} else {
ticTacLbl.setForeground(Color.blue);
ticTacLbl.setText("O");
add(ticTacLbl, 0);
isUsed = true;
}
} else {
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, new TicTacToePanel());
}
}
EDIT:
I simply added my label component in the constructor of my TicTacToePanel so that I no longer have to call revalidate() and I'm not adding components during runtime.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToePanel extends JPanel implements MouseListener{
private boolean isPlayer1Turn = true;
private boolean isUsed = false;
private JLabel ticTacLbl = new JLabel();
public TicTacToePanel(){
add(ticTacLbl, 0);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
addMouseListener(this);
}
public void mouseClicked(MouseEvent e){
}
public void mousePressed(MouseEvent e){
if (!isUsed) {
if (isPlayer1Turn) {
ticTacLbl.setForeground(Color.red);
ticTacLbl.setText("X");
isUsed = true;
} else {
ticTacLbl.setForeground(Color.blue);
ticTacLbl.setText("O");
isUsed = true;
}
}
else{
}
}
public void mouseReleased(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public static void main(String[] args){
JOptionPane.showMessageDialog(null, new TicTacToePanel());
}
}
The GUI constructor:
public TicTacToeGUI(int gameMode){
if(gameMode == 0){
amountOfPanels = 9;
TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
add(gamePanel, new GridLayout(3, 3));
setPreferredSize(new Dimension(100, 100));
for(int i = 0; i < amountOfPanels; i++){
panelArr[i] = new TicTacToePanel();
gamePanel.add(panelArr[i]);
}
}
else if(gameMode == 1){
amountOfPanels = 225;
TicTacToePanel[] panelArr = new TicTacToePanel[amountOfPanels];
add(gamePanel, new GridLayout(15, 15));
setPreferredSize(new Dimension(500, 500));
for(int i = 0; i < amountOfPanels; i++){
panelArr[i] = new TicTacToePanel();
gamePanel.add(panelArr[i]);
}
}
}
public static void main(String[] args){
JOptionPane.showMessageDialog(null, new TicTacToeGUI(0));
}
}
When you add/remove components at runtime, always call revalidate() afterwards. revalidate() makes the component refresh/relayout.
So just call revalidate() after you add the label and it will work.
If you're goal is to create a Tic Tac Toe game, then you may wish to re-think your current strategy of adding components to the GUI on the fly. Much better would be to create a grid of components, say of JLabel, and place them on the JPanel at program start up. This way you can change the pressed JLabel's text and color, and even its Icon if you want to be fancy during program run without having to add or remove components. For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class TicTacToePanel extends JPanel {
private static final int ROWS = 3;
private static final int MY_C = 240;
private static final Color BG = new Color(MY_C, MY_C, MY_C);
private static final int PTS = 60;
private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, PTS);
public static final Color X_COLOR = Color.BLUE;
public static final Color O_COLOR = Color.RED;
private JLabel[][] labels = new JLabel[ROWS][ROWS];
private boolean xTurn = true;
public TicTacToePanel() {
setLayout(new GridLayout(ROWS, ROWS, 2, 2));
setBackground(Color.black);
MyMouse myMouse = new MyMouse();
for (int row = 0; row < labels.length; row++) {
for (int col = 0; col < labels[row].length; col++) {
JLabel label = new JLabel(" ", SwingConstants.CENTER);
label.setOpaque(true);
label.setBackground(BG);
label.setFont(FONT);
add(label);
label.addMouseListener(myMouse);
}
}
}
private class MyMouse extends MouseAdapter {
#Override // override mousePressed not mouseClicked
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
String text = label.getText().trim();
if (!text.isEmpty()) {
return;
}
if (xTurn) {
label.setForeground(X_COLOR);
label.setText("X");
} else {
label.setForeground(O_COLOR);
label.setText("O");
}
// information to help check for win
int chosenX = -1;
int chosenY = -1;
for (int x = 0; x < labels.length; x++) {
for (int y = 0; y < labels[x].length; y++) {
if (labels[x][y] == label) {
chosenX = x;
chosenY = y;
}
}
}
// TODO: check for win here
xTurn = !xTurn;
}
}
private static void createAndShowGui() {
TicTacToePanel mainPanel = new TicTacToePanel();
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java keeps adding buttons! - JFrames - [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Alright, so, I am trying to make a game using a JFrame that, when you click a button, adds money, and show update some text(a JLabel).
You see, it should just update the Windows.Money variable and display ONLY the new variable on the screen, but, it adds more buttons. Please note: The money part works fine.
It's just that Java doesn't want to replace, only add.
Code:
package dev.bobdabiulder.classic.main;
import javax.swing.JLabel;
public class Bucket extends Window{
private static final long serialVersionUID = 1L;
public Bucket() throws InterruptedException {
for(int i = 0; !Window.Paused; ) {
Window.Money += 2;
this.wait(1000);
}
Window.Buckets++;
Window.BucketCounter = new JLabel("You have: " + Window.Buckets + " buckets!");
}
}
In the Windows class...
package dev.bobdabiulder.classic.main;
import java.awt.Button;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Window extends JFrame{
public static long Money = 0;
private static final long serialVersionUID = 1L;
private static Thread t1 = new Thread();
private static Thread t2 = new Thread();
private static Thread t3 = new Thread();
private static Thread t4 = new Thread();
private static Thread t5 = new Thread();
public JButton bucket = new JButton("Buy a Bucket!");
public JButton add$ = new JButton("Add Money!");
public JLabel money = new JLabel(Money + "");
public static long Buckets = 0;
public static JLabel BucketCounter = new JLabel("You have: " + Buckets + " buckets!");
public static JPanel buck = new JPanel();
public static boolean Paused = false;
static JFrame jf = new JFrame("Lol!");
//Window Method
public Window() {
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buck.add(bucket);
buck.add(money);
buck.add(add$);
buck.add(BucketCounter);
jf.setSize(500, 500);
jf.add(buck);
bucket.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(bucket)) {
try {
new Bucket();
} catch (Exception e1) {
e1.printStackTrace();
}
}
System.out.println("Action Performed!");
}
});
pack();
}
//End of ActionPerformed
//Start of start()
public static void start() {
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
//
//
//
#SuppressWarnings("deprecation")
public static void stop() {
t1.stop();
t2.stop();
t3.stop();
t4.stop();
t5.stop();
}
}
I made some requested edits, and I get errors where I put *, the errors all read:
Cannot make a static reference to the non-static field Window.(anything),
Error Spots:
for(int i = 0; !*Window.Paused; ) {
*Window.Money += 2;
this.wait(1000);
}
*Window.Buckets++;
*Window.BucketCounter = new JLabel("You have: " + *Window.Buckets + " buckets!");
Brief example of MVC, well really Model-View. What this does is uses a Swing Timer and not Threads (not directly that is) to increment a JLabel held in a different class. It also uses PropertyChangeListener and support to notify the view (the GUI) of changes in the state of the model.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.SwingPropertyChangeSupport;
/**
* http://stackoverflow.com/q/22620807/522444
* http://stackoverflow.com/a/22621767/522444
* #author Pete
*
*/
#SuppressWarnings("serial")
public class ShortMvc extends JPanel {
private JTextField moneyField = new JTextField(10);
private JTextField bucketField = new JTextField(10);
private MoneyModel model = new MoneyModel();
private Timer timer = new Timer(model.getTimerDelay(), new TimerListener());
private JButton moneyButton = new JButton("Add Money");
private JButton bucketButton = new JButton("Add Bucket");
public ShortMvc() {
moneyField.setEditable(false);
moneyField.setFocusable(false);
bucketField.setEditable(false);
bucketField.setFocusable(false);
bucketField.setText(String.valueOf(model.getBuckets()));
add(new JLabel("Money:"));
add(moneyField);
add(moneyButton);
add(new JLabel("Buckets:"));
add(bucketField);
add(bucketButton);
moneyButton.getModel().addChangeListener(new MoneyBtnModelListener());
moneyButton.setMnemonic(KeyEvent.VK_M);
bucketButton.addActionListener(new BucketButtonListener());
bucketButton.setMnemonic(KeyEvent.VK_B);
model.addPropertyChangeListener(new ModelListener());
timer.setInitialDelay(0);
}
private class BucketButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
model.incrementBuckets();
}
}
private class MoneyBtnModelListener implements ChangeListener {
private boolean pressed = false;
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (pressed == model.isPressed()) {
return;
}
pressed = model.isPressed();
if (pressed) {
timer.start();
} else {
timer.stop();
}
}
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
model.incrementMoney(model.getMoneyIncrementAmount());
}
}
private class ModelListener implements PropertyChangeListener {
private NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
public ModelListener() {
moneyField.setText(moneyFormat.format(model.getMoney()));
}
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (MoneyModel.MONEY.equals(pcEvt.getPropertyName())) {
moneyField.setText(moneyFormat.format(model.getMoney()));
}
else if (MoneyModel.BUCKETS.equals(pcEvt.getPropertyName())) {
int buckets = model.getBuckets();
bucketField.setText(String.valueOf(buckets));
timer.setDelay(model.getTimerDelay());
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Short Mvc");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ShortMvc());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MoneyModel {
public static final String MONEY = "money";
public static final String BUCKETS = "buckets";
private static final int INIT_TIMER_DELAY = 500;
public static final long MONEY_INCREMENT_AMOUNT = 2L;
private long money = 0L;
private int buckets = 1;
private int timerDelay = INIT_TIMER_DELAY;
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
this);
public void setMoney(long money) {
long oldValue = this.money;
long newValue = money;
this.money = money;
pcSupport.firePropertyChange(MONEY, oldValue, newValue);
}
public long getMoneyIncrementAmount() {
return MONEY_INCREMENT_AMOUNT;
}
public void incrementMoney(long addToMoney) {
long oldValue = this.money;
long newValue = money + addToMoney;
this.money = newValue;
pcSupport.firePropertyChange(MONEY, oldValue, newValue);
}
public long getMoney() {
return money;
}
public void setBuckets(int buckets) {
int oldValue = this.buckets;
int newValue = buckets;
this.buckets = newValue;
timerDelay = INIT_TIMER_DELAY / buckets;
pcSupport.firePropertyChange(BUCKETS, oldValue, newValue);
}
public void incrementBuckets(int incrementAmount) {
int newValue = this.buckets + incrementAmount;
setBuckets(newValue);
}
// increment by one
public void incrementBuckets() {
incrementBuckets(1);
}
public int getBuckets() {
return buckets;
}
public int getTimerDelay() {
return timerDelay;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
}
Note that I can't use an ActionListener for this to work since an ActionListener only gets activated when the button is released. I'm assuming that you want to accumulate money when the button is pressed, and then stop accumulating when it is released. To do this, you must extract the JButton's model, add a ChangeListener to it, and then react to changes to the model's isPressed() method. I use it to start and stop the Swing Timer that increments the model.
Edit
Next iteration with better MVC (model-view-control) separation:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.text.JTextComponent;
/**
* http://stackoverflow.com/q/22620807/522444
* http://stackoverflow.com/a/22621767/522444
* #author Pete
*
*/
public class ShortMvc {
private static void createAndShowGui() {
ShortView view = new ShortView();
MoneyModel model = new MoneyModel();
ShortControl control = new ShortControl(model, view);
control.init();
JFrame frame = new JFrame("Short MVC");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(view.getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ShortView {
private JTextField moneyField = new JTextField(10);
private JTextField bucketField = new JTextField(10);
private JButton moneyButton = new JButton();
private JButton bucketButton = new JButton();
private JPanel mainPanel = new JPanel();
public ShortView() {
moneyField.setEditable(false);
moneyField.setFocusable(false);
bucketField.setEditable(false);
bucketField.setFocusable(false);
mainPanel.add(new JLabel("Money:"));
mainPanel.add(moneyField);
mainPanel.add(moneyButton);
mainPanel.add(new JLabel("Buckets:"));
mainPanel.add(bucketField);
mainPanel.add(bucketButton);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTextComponent getMoneyField() {
return moneyField;
}
public JTextComponent getBucketField() {
return bucketField;
}
public AbstractButton getMoneyButton() {
return moneyButton;
}
public AbstractButton getBucketButton() {
return bucketButton;
}
}
#SuppressWarnings("serial")
class ShortControl {
private MoneyModel model;
private ShortView view;
private Timer timer;
private MoneyBtnAction moneyBtnAction = new MoneyBtnAction("Add Money", KeyEvent.VK_M);
private BucketButtonAction bucketAction = new BucketButtonAction("Add Buckets", KeyEvent.VK_B);
public ShortControl(MoneyModel model, ShortView view) {
this.model = model;
this.view = view;
timer = new Timer(model.getTimerDelay(), new TimerListener());
}
public void init() {
timer.setInitialDelay(0);
view.getBucketField().setText(String.valueOf(model.getBuckets()));
view.getMoneyButton().setAction(moneyBtnAction);
view.getMoneyButton().getModel().addChangeListener(moneyBtnAction);
view.getBucketButton().setAction(bucketAction);
model.addPropertyChangeListener(new ModelListener());
}
private class BucketButtonAction extends AbstractAction {
public BucketButtonAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
model.incrementBuckets();
}
}
private class MoneyBtnAction extends AbstractAction implements ChangeListener {
private boolean pressed = false;
public MoneyBtnAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// empty
}
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (pressed == model.isPressed()) {
return;
}
pressed = model.isPressed();
if (pressed) {
timer.start();
} else {
timer.stop();
}
}
}
private class ModelListener implements PropertyChangeListener {
private NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
public ModelListener() {
view.getMoneyField().setText(moneyFormat.format(model.getMoney()));
}
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (MoneyModel.MONEY.equals(pcEvt.getPropertyName())) {
view.getMoneyField().setText(moneyFormat.format(model.getMoney()));
}
else if (MoneyModel.BUCKETS.equals(pcEvt.getPropertyName())) {
int buckets = model.getBuckets();
view.getBucketField().setText(String.valueOf(buckets));
timer.setDelay(model.getTimerDelay());
}
}
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
model.incrementMoney(model.getMoneyIncrementAmount());
}
}
}
class MoneyModel {
public static final String MONEY = "money";
public static final String BUCKETS = "buckets";
private static final int INIT_TIMER_DELAY = 500;
public static final long MONEY_INCREMENT_AMOUNT = 2L;
private long money = 0L;
private int buckets = 1;
private int timerDelay = INIT_TIMER_DELAY;
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(
this);
public void setMoney(long money) {
long oldValue = this.money;
long newValue = money;
this.money = money;
pcSupport.firePropertyChange(MONEY, oldValue, newValue);
}
public long getMoneyIncrementAmount() {
return MONEY_INCREMENT_AMOUNT;
}
public void incrementMoney(long addToMoney) {
long oldValue = this.money;
long newValue = money + addToMoney;
this.money = newValue;
pcSupport.firePropertyChange(MONEY, oldValue, newValue);
}
public long getMoney() {
return money;
}
public void setBuckets(int buckets) {
int oldValue = this.buckets;
int newValue = buckets;
this.buckets = newValue;
timerDelay = INIT_TIMER_DELAY / buckets;
pcSupport.firePropertyChange(BUCKETS, oldValue, newValue);
}
public void incrementBuckets(int incrementAmount) {
int newValue = this.buckets + incrementAmount;
setBuckets(newValue);
}
// increment by one
public void incrementBuckets() {
incrementBuckets(1);
}
public int getBuckets() {
return buckets;
}
public int getTimerDelay() {
return timerDelay;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
}
Ok, this should help a bit... missing Timer but you can get an idea of how to manage ActionListeners:
Main class
public class WindowInit{
public static void main(String args[]){
WindowHelp wh = new WindowHelp();
}
}
WindowHelp (This one does the magic)
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.event.*;
public class WindowHelp{
JButton b1;
JButton b2;
JLabel label;
long money;
long buckets;
JFrame jf;
Timer timer;
public WindowHelp(){
money = 0;
buckets = 0;
b1 = new JButton("Add buckets");
b2 = new JButton("Add money");
label = new JLabel("");
jf = new JFrame("My Game");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buckets += 2;
label.setText("Buckets: " + buckets);
}
});
b1.setBounds(50,50,100,30);
b2.setBounds(200,50,100,30);
label.setBounds(300,50,200,30);
jf.add(b1);
jf.add(b2);
jf.add(label);
jf.setSize(500,600);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Yes, one is the main class you compile "WindowInit" and run that one.
For timers, gimme some time while I implement it.

Fixing method latency in Java

Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}

Categories