I'm new to Java Swing and I have been working on creating a Connect 4 Game which supports multiplayers through a server with a gameRoom. I have been working on this particular problem for almost 2 days and while solving it have fixed problems such as stopped the use of Thread.sleep and thoroughly tested that the Game object is passed on correctly to and from the server.
The way I architected is that each move is submitted through the model's make move command. In order to refresh the GUI, the server sends back a new Game object to the model and marks the controller attribute 'setRepaint' as true. Then, a timer periodically checks if this attribute is true and calls the repaintGrid() method.
After many hours of trying to get this to work, I cannot get the game panels to repaint.
Some points which might help:
If I quit the application and restart it with a Game object that already has moves on it, the panels are painted. The problem is with the repaint method.
The model is static and gets it Game attribute updated every time the Connect4App.model.getGameFromServer() is called. Not sure if this would cause problems but if I print the panels that are being repainted as red/blue, I can verify that the game object is updated successfully by the server on each iteration.
The frame hierarchy is the following: The guiMain is a container for the gamePanel which has a gridlayout, each filled in by a GridPanel panel. The Grid panels are essentially the slots for the tokens of the Connect4 Game and those are the ones that I try to update in the repaintGrid method
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GameController {
MouseAdapter me;
private JPanel gamePanel;
private boolean setRepaint = false;
/**
* Constructor for the Game Controller. Takes in a view and a model
*
* #param view
* #param model
*/
public GameController() {
setupGridPanels();
setupMouseAdapter();
Connect4App.frame.setContentPane(Connect4App.guiMain);
Connect4App.frame.setTitle("Game View");
goIntoTimer();
}
/**
* Repaint Boolean used by timer. Set to true by external program
*/
public void setRepaint() {
this.setRepaint = true;
}
/**
* Swing Timer which checks if it needs to repaint every 8 seconds and if
* so, calls repaintGrid
*/
private void goIntoTimer() {
Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connect4App.model.getGameFromServer();
if (setRepaint == true) {
repaintGrid();
setRepaint = false;
}
}
});
timer.setRepeats(true);
timer.setDelay(8000);
timer.start();
}
/**
* Sets up the Initial Game Panels in the Connect4App.guiMain panel
*/
private void setupGridPanels() {
this.gamePanel = new JPanel();
this.gamePanel.removeAll();
// setting up the layout for, the game board.
this.gamePanel.setLayout(new GridLayout(0, Connect4App.model.getGame().getGrid()[0].length));
int numberOfRows = Connect4App.model.getGame().getGrid().length;
int numberOfColumns = Connect4App.model.getGame().getGrid()[0].length;
for (int r = 0; r < numberOfRows; r++) {
for (int c = 0; c < numberOfColumns; c++) {
Connect4App.guiMain.setCircleArc(r, c, new GridPanel(r, c));
this.gamePanel.add(Connect4App.guiMain.getCircleArcs()[r][c]);
}
}
Connect4App.guiMain.add(this.gamePanel);
}
/**
* Sets up the mouse pressed event handleres for every panel
*/
private void setupMouseAdapter() {
MouseAdapter mc = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent mc) {
GridPanel cell = (GridPanel) mc.getSource();
// this is the column that should go in the MakeMove message
int column = cell.getColumn();
int row = cell.getRow();
if (Connect4App.model.getGame().getGrid()[row][column].getState() == 0) {
System.out.println("attempting to make move");
Connect4App.model.makeMove(column);
}
}
};
for (int r = 0; r < Connect4App.model.getGame().getGrid().length; r++) {
for (int c = 0; c < Connect4App.model.getGame().getGrid()[0].length; c++) {
Connect4App.guiMain.getCircleArcs()[r][c].addMouseListener(mc);
}
}
}
void repaintGrid() {
// --> This is supposed to be working
System.out.println("repainting");
for (int r = 0; r < Connect4App.model.getGame().getGrid().length; r++) {
for (int c = 0; c < Connect4App.model.getGame().getGrid()[0].length; c++) {
Connect4App.guiMain.getCircleArcs()[r][c].validate();
Connect4App.guiMain.getCircleArcs()[r][c].repaint();
}
}
}
}
Any help would be appreciated :-D
It turns out the I was having a problem with sending the same object back and fourth through objectoutputstreams (the game state) without reseting the streams and so this was causing the client not to receive updates all of the times. The repainting code above was working. Closing the thread, thanks again.
Related
This is my first post on this site, but I have spent a lot of time looking for a solution to my problem and just can't seem to find it anywhere. Essentially, I've been tasked with developing the Game of Life program in a Java applet. Our team wants to change the elements in our array(which represent the 'cells') based on the color of the cell, which the user changes via mouse click(red = living(1), white = dead(0)). So, we tried writing the following code:
^^^EDIT^^^
I've gotten the array to populate by doing it manually. The only problem I have now is that the nested for loops that are meant to change the values are only looking on the lines of the grid, not the cells themselves. Here is the whole class for those who requested. Once again, thanks for your help!
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Arrays;
/**
* Class ForCs120 - write a description of the class here
*
* #author (your name)
* #version (a version number)
*/
public class ForCs120 extends JApplet
{
// instance variables - replace the example below with your own
int oldx, oldy;
JFrame myFrame = new JFrame();
JPanel aPanel = new JPanel();
JButton aButton = new JButton("Next Generation");
JButton clearButton = new JButton("Clear Board");
int[][] thisGen = new int[40][40];
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
for(int i = 0; i<40; i++)
{
for(int j = 0; j<40; j++)
{
thisGen[i][j] = 0;
}
}
Graphics g = getGraphics();
for(int i = 0; i<40; i++)
{
for(int j = 0; j<40; j++)
{
g.getColor();
if(g.getColor() == Color.red)
{
thisGen[i][j] = 1;
}
else
{
thisGen[i][j] = 0;
}
}
g.drawString(Arrays.deepToString(thisGen), 20, 20);
}
}
}
ButtonListener aButtonListener = new ButtonListener();
private class ClearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Graphics g = getGraphics();
g.drawString("You need to add code to clear the board", 10,50);
}
}
ClearButtonListener clear = new ClearButtonListener();
/**
* Called by the browser or applet viewer to inform this JApplet that it
* has been loaded into the system. It is always called before the first
* time that the start method is called.
*/
public void init()
{
// this is a workaround for a security conflict with some browsers
// including some versions of Netscape & Internet Explorer which do
// not allow access to the AWT system event queue which JApplets do
// on startup to check access. May not be necessary with your browser.
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
oldx = -1;
oldy = -1;
this.addMouseListener(myListener);
aButton.setSize(150,150);
aButton.addActionListener(aButtonListener);
clearButton.addActionListener(clear);
myFrame.setSize(200,200);
this.setSize(400,400);
aPanel.add(aButton);
aPanel.add(clearButton);
myFrame.add(aPanel);
myFrame.setVisible(true);
// provide any initialisation necessary for your JApplet
}
/**
* Called by the browser or applet viewer to inform this JApplet that it
* should start its execution. It is called after the init method and
* each time the JApplet is revisited in a Web page.
*/
public void start()
{
// provide any code requred to run each time
// web page is visited
}
/**
* Called by the browser or applet viewer to inform this JApplet that
* it should stop its execution. It is called when the Web page that
* contains this JApplet has been replaced by another page, and also
* just before the JApplet is to be destroyed.
*/
public void stop()
{
// provide any code that needs to be run when page
// is replaced by another page or before JApplet is destroyed
}
/**
* Paint method for applet.
*
* #param g the Graphics object for this applet
*/
private class MousePressedListener implements MouseListener
{
public void mousePressed(MouseEvent e)
{
//int [][] firstGen = new int[40][40]
//for(int i=0;
Graphics g = getGraphics();
int x = e.getX();
int y = e.getY();
int d = x/10;
int c = y/10;
g.setColor(Color.red);
g.fillRect(d*10, c*10, 10, 10);
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
Graphics g = getGraphics();
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
}
MousePressedListener myListener = new MousePressedListener();
public void paint(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0,0,400,400);
g.setColor(Color.black);
for(int i = 0; i <=this.getWidth(); i+=10)
{
g.drawLine(i, 0, i, 400);
g.drawLine(0, i, 400, i);
}
}
/**
* Called by the browser or applet viewer to inform this JApplet that it
* is being reclaimed and that it should destroy any resources that it
* has allocated. The stop method will always be called before destroy.
*/
public void destroy()
{
// provide code to be run when JApplet is about to be destroyed.
}
/**
* Returns information about this applet.
* An applet should override this method to return a String containing
* information about the author, version, and copyright of the JApplet.
*
* #return a String representation of information about this JApplet
*/
public String getAppletInfo()
{
// provide information about the applet
return "Title: \nAuthor: \nA simple applet example description. ";
}
/**
* Returns parameter information about this JApplet.
* Returns information about the parameters than are understood by this JApplet.
* An applet should override this method to return an array of Strings
* describing these parameters.
* Each element of the array should be a set of three Strings containing
* the name, the type, and a description.
*
* #return a String[] representation of parameter information about this JApplet
*/
public String[][] getParameterInfo()
{
// provide parameter information about the applet
String paramInfo[][] = {
{"firstParameter", "1-10", "description of first parameter"},
{"status", "boolean", "description of second parameter"},
{"images", "url", "description of third parameter"}
};
return paramInfo;
}
}
I don't have any exception in your code only two recommendation.
int[][] thisGen = new int[40][40];
public void actionPerformed(ActionEvent e){
Graphics g = getGraphics();
for(int i = 0; i<40; i++)
{
for(int j = 0; j<40; j++)
{
if(g.getColor() == Color.red)
{
thisGen[i][j] = 1;
}
else
{
thisGen[i][j] = 0;
}
}
}
//////1. I don't feel there is any link between these two loops
for(int x = 0; x<thisGen.length; x++)
{
for(int y = 0; y<thisGen[x].length; y++) //2. replaced o by x if you've Jagged array
{
System.out.println(thisGen[x][y] +" ");
}
System.out.println();
}
}
EDIT :
A MCVE version of my code has been made to help debug it. It reproduces my bug. The purpose of my code is doing a Memory game. Which means that when it is your turn, you "open" a card, then another one. If they form a pair, they don't get turned over, they stay open. Otherwise, you turn them back over and try to find a pair on the next turn.
Simply put, the bug is : when you are opening the second card of your turn and both cards don't form a pair, the second one never gets opened!
Hopefully, this version of my code will help you to find the bug, which will help me a lot!
I have put the code on Github : https://gist.github.com/anonymous/e866671d80384ae53b53
(And you will find it attached at the end of the question)
Explanation of the issue
I am having fun on doing a little Memory game in JavaFX and I came across this strange behavior where the card I click on (represented by a custom class that extends the Button class) never changes the image displayed.
Normally, when I click on the card, it "opens" itself by changing the graphic it displays.
The strange and annoying thing is that it only happens in a specific case.
The behavior of my card is correct when I "open" the first card of the turn of the player. It also works when I "open" a second one and both cards are a pair. Sadly, it doesn't work only in the case where I want to open a second card and it doesn't match as a pair with the first one.
I modified the Button class by adding openCard() and closeCard() methods. Those methods will set a specific graphic on the button-card.
I will now show some code but it is hard to tell what might be the part that is making this behavior happen. Even more so that I am using Eclipse but can't possibly figure out how to debug a JavaFX app with breakpoints (I am using console prints) because the app will eventually crash when I reach my breakpoints and start crawling through the lines of code.
The code
Firstly, the modified Button class :
public class Card extends Button{
private String cardDesign;
public Card(int row, int column){
this.setGraphic(new ImageView("/resources/card_back.png"));
this.setBackground(new Background(new BackgroundFill(Color.SLATEGRAY,
new CornerRadii(6), null)));
}
public void setOpenCardDesign(String design){ cardDesign = design; }
public void openCard(){ this.setGraphic(new ImageView(cardDesign)); }
public void closeCard(){
this.setGraphic(new ImageView("/resources/card_back.png"));
}
}
Now the controller class, the event is set on a MouseEvent. There is more code in this controller (like checking if there is a pair), but this isn't an issue here I think as the problem is already at the line where I call the method to open the card.
I use the getSource() method here because my cards are arranged in a gridPane and I need to know which one has been clicked on.
#Override
public void handle(MouseEvent event) {
//Get the card that was clicked on
Card card = (Card) event.getSource();
//Open the card
card.openCard();
//Do some more after this...
}
That's pretty much it as from what I could figure out.
As already stated, I tried to check if the method openCard() is being called. It is as some comment printed in my console showed up. I even added some console printing just before and just after the line where I set the graphic and they both are showing up. I can't know for sure what happens when my app reaches the setGraphic() line as nothing is showing up in my app (the card remains closed).
Any hint would help because I am slowly sinking in madness right now.
Thank you in advance.
The MCVE version of my code
The card object : Card.java
package memory;
import javafx.scene.control.Button;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.paint.Color;
public class Card extends Button{
//-------------------------------------------------
//Store the position of the card
private int row;
private int column;
//-------------------------------------------------
//Constructor
public Card(int row, int column){
//Give the cards a specific color at init
this.setBackground(new Background(new BackgroundFill(Color.DEEPSKYBLUE,
new CornerRadii(6), null)));
this.setText("CLOSED");
this.row = row;
this.column = column;
}
//-------------------------------------------------
//Open the card
public void openCard(){
System.out.println("OPEN");
//Cards are red when open
this.setBackground(new Background(new BackgroundFill(Color.RED,
new CornerRadii(6), null)));
this.setText("OPEN");
}
//-------------------------------------------------
//Close the card
public void closeCard(){
System.out.println("CLOSE");
//Cards are blue when closed
this.setBackground(new Background(new BackgroundFill(Color.DEEPSKYBLUE,
new CornerRadii(6), null)));
this.setText("CLOSED");
}
//-------------------------------------------------
//Getters for row and column info
public int getRow() { return row; }
public int getColumn() { return column; }
}
The main (includes the view and start point of the app) : Main.java
package memory;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Main extends Application {
//-------------------------------------------------
//The layout and the cards
GridPane gridCard = new GridPane();
static Card [][] cardArray;
//The event handler
private static EventHandler<MouseEvent> handler;
//The array which remembers the pairs and the reminder of last open card
static int[][] indexArray;
static int index;
//Boolean array to check if the card is already open
static boolean[][] isOpen;
//Number of pairs to find
static int pairs = 5;
//-------------------------------------------------
//Cheap main
public static void main(String[] args) {
Application.launch(args);
}
//-------------------------------------------------
#Override
public void start(Stage primaryStage) throws Exception {
//Init the event handler
handler = new Controller();
//Some formatting for the grid pane
gridCard.setHgap(10);
gridCard.setVgap(10);
gridCard.setPadding(new Insets(0, 10, 0, 10));
gridCard.setAlignment(Pos.CENTER);
//Creating our card board, index array and bool array
cardArray = new Card [2][5];
indexArray = new int [2][5];
isOpen = new boolean [2][5];
//Adding the cards to our card array
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
cardArray[i][j] = new Card(i, j);
//Make those buttons look like cards
cardArray[i][j].setPrefHeight(100);
cardArray[i][j].setPrefWidth(70);
//Register the event
cardArray[i][j].addEventHandler(MouseEvent.MOUSE_CLICKED, gameController());
//Add those cards
gridCard.add(cardArray[i][j], j, i);
//Set the pairs (no randomness here)
indexArray[i][j] = j+1;
}
}
//Print out the indexes of all the cards
System.out.println("----------------");
System.out.println("Card indexes :");
for (int i = 0; i < indexArray.length; i++) {
System.out.println();
for (int j = 0; j < indexArray[0].length; j++) {
System.out.print(indexArray[i][j]+ " | ");
}
System.out.println();
}
System.out.println("----------------");
//Set BorderPane
BorderPane root = new BorderPane();
root.setBackground(new Background(new BackgroundFill(Color.BLACK,
CornerRadii.EMPTY, null)));
root.setCenter(gridCard);
//Set the stage
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Memory Test");
primaryStage.show();
}
//-------------------------------------------------
//Getter for the event handler
public static EventHandler<MouseEvent> gameController() {
return handler;
}
//-------------------------------------------------
//Getter, Setter and "resetter" for the index
public static void resetIndex() { index = 0; }
public static int getIndex() { return index; }
public static void setIndex(int i) {
index = i;
}
//-------------------------------------------------
}
The controller : Controller.java
package memory;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseEvent;
public class Controller implements EventHandler<MouseEvent>{
//-------------------------------------------------
#Override
public void handle(MouseEvent event) {
//Get the card which cas clicked on
Card card = (Card) event.getSource();
//If the card was already open, don't do anything
if (!Main.isOpen[card.getRow()][card.getColumn()]) {
//Open the card
card.openCard();
//We opened the first card of the turn
if (Main.getIndex() == 0) {
//Set the card as open
Main.isOpen[card.getRow()][card.getColumn()] = true;
//Remember the index
Main.setIndex(Main.indexArray[card.getRow()][card.getColumn()]);
System.out.println("index: "+Main.getIndex());
//We opened the second card
}else if (Main.getIndex() != 0) {
//Check if it is a pair
if (Main.getIndex() == Main.indexArray[card.getRow()][card.getColumn()]) {
//Decrement the number of pairs
Main.pairs--;
//Open the second card
Main.isOpen[card.getRow()][card.getColumn()] = true;
//Reset the index
Main.resetIndex();
}else{ //Close both cards if it isn't a pair
//Wait 0.7 second to let the player remember the cards
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Close the current card
card.closeCard();
System.out.println("index : " + Main.indexArray[card.getRow()][card.getColumn()]);
Main.isOpen[card.getRow()][card.getColumn()] = false;
//Close the first opened card by looking at the index
//It closes both cards with the same index, but it doesn't matter
//as the pair hasn't been found anyway
for (int i = 0; i < Main.indexArray.length; i++) {
for (int j = 0; j < Main.indexArray[0].length; j++) {
if (Main.getIndex() == Main.indexArray[i][j]) {
Main.cardArray[i][j].closeCard();
System.out.println("index: " + Main.indexArray[i][j]);
Main.isOpen[i][j] = false;
}
}
}
//Reset the index of last opened card
Main.resetIndex();
}
}
}
//Check endgame
if (Main.pairs == 0) {
//Show a dialog box
Alert incorrectPairs = new Alert(AlertType.INFORMATION);
incorrectPairs.setTitle("GAME OVER");
incorrectPairs.setHeaderText("The game is over");
incorrectPairs.setContentText("You found all the pairs, congrats!");
incorrectPairs.showAndWait();
}
}
//-------------------------------------------------
}
You're blocking the UI thread with Thread.sleep(...). That prevents any pending changes from being repainted, so you don't see the first update at all; you only see the subsequent updates after the pause is complete.
The simplest way to implement a pause on the UI thread is to use a PauseTransition from the JavaFX animation API. Basically, you do
PauseTransition pause = new PauseTransition(Duration.millis(700));
pause.setOnFinished(e -> {
// code to execute after pause...
});
pause.play();
In your case, you probably want to disable the user interface, so the user cannot click on anything during the pause, so you could do something like
PauseTransition pause = new PauseTransition(Duration.millis(700));
pause.setOnFinished(e -> {
card.closeCard();
// ... etc...
card.getParent().setDisable(false);
});
card.getParent().setDisable(true);
pause.play();
I am coding a little game in which i have taken a grid of JButtons in a JFrame and i want to refresh the colors of the buttons contained in a JFrame,which is already visible.As explained below
void foo(){
mainFrame.setVisible(true);//mainFrame is defined at class level.
//color update code for the buttons.
mainFrame.setVisible(true);
}
Result i am getting is not as expected and my screen gets freeze .Isn't it the right way to achieve what i wanted?
EDIT
ok i am explaining it in detail what i want to achieve.i have a class,as:-
import javax.swing.*;
import java.awt.*;
import java.util.*;
class Brick extends JButton{
public void setRandomColors(){
int random = (int) (Math.random()*50);
if(random%13==0){
this.setBackground(Color.MAGENTA);
}
else if(random%10==0){
this.setBackground(Color.red);
}
else if(random%9==0){
this.setBackground(Color.yellow);
}
else if(random%7==0){
this.setBackground(Color.orange);
}
else if(random%2==0){
this.setBackground(Color.cyan);
}
else{
this.setBackground(Color.PINK);
}
}
public void setBlackColor(){
this.setBackground(Color.black);
}
}
class Grid {
JFrame mainGrid = new JFrame();
ArrayList<Brick> bunchOfBricks = new ArrayList<>();
int gridLength = 8;//gridlenth is equals to gridweight as i have considered a Square grid.
int totalBricks = gridLength*gridLength;
public void formBunchOfBricks(){
for(int i=0;i<totalBricks;i++){
bunchOfBricks.add(new Brick());
}
}
public void formColoredGrid(){
Brick aBrick;
mainGrid.setLayout(new GridLayout(8,8));
for(int i=0;i<totalBricks;++i){
aBrick = (bunchOfBricks.get(i));
aBrick.setRandomColors();
mainGrid.add(aBrick);
}
mainGrid.setVisible(true);//its ok upto here iam getting randomly colored Frame of Bricks or so called JButtons.
delay(15);//Sorry for this one,i warn you not to laugh after looking its defination.
}
/*
I want following function to do following things:-
1.it should firstly display the Grid whose all buttons are black Colored.
2.After some time the original colored,first Row of grid formed by formColoredGrid should be displayed and all the rest Rows should be black.
3.Then second row turns colored and all other rows should be black......and so on upto last row of Grid.
*/
public void movingRows(){
setGridBlack();
delay(1);//see in upper method,for this horrible thing.
for(int i=0;i<gridLength;++i){
setGridBlack();
for (int j=0;j<gridLength;++j){
Brick aBrick = bunchOfBricks.get((gridLength*i)+j);
aBrick.setRandomColors();//Bricks are colored Row by Row.
}
delay(5);//already commented this nonsense.
mainGrid.setVisible(true);//using setVisible again,although this frame is already visible,when i called formColoredGrid.
setGridBlack();
}
//oh! disappointing,i have almost broken my arm slamming it on table that why the function result in a screen full of black buttons.
}
public void setGridBlack(){
for(int i=0;i<totalBricks;i++){
bunchOfBricks.get(i).setBlackColor();
}
}
public void delay(int a){
for ( int i=0;i<90000000;++i){
for(int j=0;j<a;++j){
}
}
}
public static void main(String args[]){
Grid g1 = new Grid();
g1.formBunchOfBricks();
g1.formColoredGrid();
g1.movingRows();
}
}
Please Help me what is the way out?
Your problem is in code not shown here:
//color update code for the buttons.
You're likely running a loop that never ends on the Swing event thread, possibly a never-ending while loop that polls the state of something(a guess), freezing your GUI. Solution: don't do this; don't use a continuous polling loop. Instead, change the colors based on responses to events as Swing is event-driven.
For better more specific help, please show the offending code and tell us more about your program.
Edit
If you're trying to show colored rows, one by one marching down the board, then my guess is right, you'll want to use a Swing Timer, one that uses an int index to indicate which row is being displayed in color. You'd increment the index inside of the Timer's ActionPerformed class, and then when all rows have been displayed stop the Timer. For example something like so:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyGrid extends JPanel {
private static final int GRID_LENGTH = 8;
private static final Color BTN_BACKGROUND = Color.BLACK;
private static final Color[] COLORS = { Color.MAGENTA, Color.CYAN,
Color.RED, Color.YELLOW, Color.ORANGE, Color.PINK, Color.BLUE,
Color.GREEN };
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final int TIMER_DELAY = 800;
private JButton[][] buttonGrid = new JButton[GRID_LENGTH][GRID_LENGTH];
private Map<JButton, Color> btnColorMap = new HashMap<>();
private Random random = new Random();
public MyGrid() {
setLayout(new GridLayout(GRID_LENGTH, GRID_LENGTH));
for (int row = 0; row < buttonGrid.length; row++) {
for (int col = 0; col < buttonGrid[row].length; col++) {
JButton btn = new JButton();
btn.setBackground(BTN_BACKGROUND);
// !! add action listener here?
add(btn);
buttonGrid[row][col] = btn;
}
}
new Timer(TIMER_DELAY, new TimerListener()).start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void resetAllBtns() {
for (JButton[] row : buttonGrid) {
for (JButton btn : row) {
btn.setBackground(BTN_BACKGROUND);
}
}
}
private class TimerListener implements ActionListener {
private int row = 0;
#Override
public void actionPerformed(ActionEvent e) {
resetAllBtns(); // make all buttons black
if (row != buttonGrid.length) {
for (int c = 0; c < buttonGrid[row].length; c++) {
int colorIndex = random.nextInt(COLORS.length);
Color randomColor = COLORS[colorIndex];
buttonGrid[row][c].setBackground(randomColor);
// !! not sure if you need this
btnColorMap.put(buttonGrid[row][c], randomColor);
}
row++;
} else {
// else we've run out of rows -- stop the timer
((Timer) e.getSource()).stop();
}
}
}
private static void createAndShowGui() {
MyGrid mainPanel = new MyGrid();
JFrame frame = new JFrame("MyGrid");
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();
}
});
}
}
Please have a look at the Swing Timer Tutorial as well.
Edit 2
You ask:
but what is the reason of failure of this program,is it the useless delay function?
Your delay method does nothing but busy calculations on the Swing event thread:
public void delay(int a) {
for (int i = 0; i < 90000000; ++i) {
for (int j = 0; j < a; ++j) {
}
}
}
It's little different from a crude attempt at calling Thread.sleep(...), and is crude because you can't explicitly control how long it will run as you can with thread sleep. Again, the problem is that you're making these calls on the Swing event dispatch thread or EDT, the single thread that is responsible for all Swing drawing and user interactions. Blocking this thread will block your program making it non-running or frozen.
This is my first attempt at using a GUI layout in Java. I am trying to create a simple memory card game, where the user flips over two cards, and tries to get a match, and if there's no match they flip back over, if there's a match they stay flipped until you get all the matches. I might have made it hard on myself though in that I made the whole game dynamic to the constructor variables that define the number of columns and rows of cards. I thought this was better than hard-coding a certain value in, but now I'm having trouble putting the images in my img folder onto my cards.
I understand that variables of variables are not permitted in Java & this is really hard for me to adapt to as a ColdFusion developer. Can you help me think of ways to accomplish this this the proper way in Java?
Here is a simplified version of my code.
import javax.swing.JFrame;
public class MemoryApp
{
public static void main(String args[])
{
//Creates a new game with 3 columns and 4 rows
final CardGame myGame = new CardGame(3, 4);
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI(myGame.getCols(), myGame.getRows());
}
});
}
private static void createAndShowGUI(int c, int r) {
//Create and set up the window.
Window frame = new Window("GridLayoutDemo", c, r);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
Card game class:
public class CardGame
{
private int cols, rows;
public CardGame(int c, int r)
{
cols = c;
rows = r;
}
public int getCols(){
return cols;
}
public int getRows(){
return rows;
}
}
The window with the grid layout:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
public class Window extends JFrame
{
private int cols, rows;
GridLayout windowGrid = new GridLayout(1,1);
public Window(String t, int c, int r)
{
super(t);
cols = c;
rows = r;
windowGrid.setColumns(c);
windowGrid.setRows(r);
}
public void addComponentsToPane(final Container pane)
{
final JPanel compsToExperiment = new JPanel();
compsToExperiment.setLayout(windowGrid);
JPanel controls = new JPanel();
controls.setLayout(new GridLayout(cols,rows));
int countCard = (cols * rows) / 2;
/**
* Add buttons to experiment with Grid Layout.
* This is where I'd like to be able to loop through
* countCard and create the required number of buttons
* as well as put images on the buttons like so:
*
* ImageIcon image1 = new ImageIcon(getClass().getResource("card1.png"));
* through
* ImageIcon image1 = new ImageIcon(getClass().getResource("card" & cardCount & ".png"));
*
* Below is how I would attempt this in ColdFusion- I know
* the variable of variables syntax is invalid, it is just
* to show you what I mean.
*/
// for(int i = 0; i < countCard; i++;)
// {
// compsToExperiment.add(new JButton("../img/card" & i & ".png"));
// ImageIcon variables["image" & i] = new ImageIcon(getClass().getResource("card" & i & ".png"));
// imageButton.setIcon(variables["image" & i]);
// etc. with ButtonClickEventHandler, haven't gotten that far yet
// }
pane.add(compsToExperiment, BorderLayout.NORTH);
pane.add(new JSeparator(), BorderLayout.CENTER);
}
}
Based on the code commented-out code that you posted so far, one approach could be like this:
public class Window extends JFrame
{
...
// A java.util.List that stores all the buttons, so
// that their icons may be changed later
private List<JButton> buttons = new ArrayList<JButton>();
// A java.util.List that stores all the ImageIcons that
// may be placed on the buttons
private List<ImageIcon> imageIcons = new ArrayList<ImageIcon>();
public void addComponentsToPane(final Container pane)
{
...
for(int i = 0; i < countCard; i++;)
{
// String concatenation is done with "+" in Java, not with "&"
String fileName = "card" + i + ".png";
// Create the icon and the button containing the icon
ImageIcon imageIcon = new ImageIcon(getClass().getResource(fileName));
JButton button = new JButton(imageIcon);
// Add the button to the main panel
compsToExperiment.add(button);
// Store the button and the icon in the lists
// for later retrieval
imageIcons.add(imageIcon);
buttons.add(button);
// Attach an ActionListener to the button that will
// be informed when the button was clicked.
button.addActionListener(createActionListener(i));
}
}
private ActionListener createActionListener(final int cardIndex)
{
return new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
clickedCardButton(cardIndex);
}
};
}
private void clickedCardButton(int cardIndex)
{
System.out.println("Pressed button for card "+cardIndex);
// Here you can change the icons of the buttons or so...
JButton button = buttons.get(cardIndex);
ImageIcon imageIcon = imageIcons.get(cardIndex);
....
}
You mentioned that this is your first attempt to build a GUI with Java. So I assume that this is only intended for "practicing". If your intention was to build a "real application", you should rather consider some Model-View-Controller (MVC) approach for this.
I am putting together a slideshow program that will measure a user's time spent on each slide. The slideshow goes through several different magic tricks. Each trick is shown twice. Interim images are shown between the repetition. Transition images are shown between each trick.
On the first repetition of a trick the JPanel color flashes on the screen after a click before the next image is shown. This doesn't happen during the second repetition of the same trick. It's possible that the image is taking too long to load.
Is there an easy way to pre-load the images so that there isn't a delay the first time through?
NOTE: Original code deleted.
EDIT 1/10/2013: This code now works on slower machines. trashgod's second addendum helped the most. The mouseClick control structure periodically asks SwingWorker classes to load 40 images or less of the current trick while also setting the used images to null. I have simplified my code down for this to just two Image[]s and added a main method so it stands alone. Images are still required to run though. This is now pretty bare bones code, and if you're trying to make a slideshow with a lot of images I think it would be a good place to start.
NOTE: I think I figured out how to properly implement SwingWorker while still using multiple Image[]s. trashgod and kleopatra is this implementation in-line with what you were suggesting? I didn't end up using publish and process since I couldn't figure out how to get that to work appropriately with an indexed array, but because the StringWorker doesn't load all images in the array (only 40), and the code calls StringWorker every 20 images, there should be a pretty good buffer.
EDIT 1/10/2013 Changed out MouseListener by instead extending MouseAdapter on my Mouse class. Also fixed my paintComponent method to include a call to super.paintComponent(g).
Added publish/process methods to my SwingWorker class ImageWorker. Added a wrapper class, ArrayWrapper to allow passing imageArray[i] and its corresponding index int i with publish to process.
package slideshow3;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.List;
public class SlideShow3 extends JFrame
{
//screenImage will be replaced with each new slide
private Image screenImage;
private int width;
private int height;
//Create panel for displaying images using paintComponent()
private SlideShow3.PaintPanel mainImagePanel;
//Used for keybinding
private Action escapeAction;
//Image array variables for each trick
private Image[] handCuffs; //h
private Image[] cups; //c
//Used to step through the trick arrays one image at a time
private int h = 0;
private int c = 0;
//Used by timeStamp() for documenting time per slide
private long time0 = 0;
private long time1;
public SlideShow3()
{
super();
//Create instance of each Image array
handCuffs = new Image[50];
cups = new Image[176];
//start(handCuffsString);
start("handCuffs");
try
{
screenImage = ImageIO.read(new File("images/begin1.jpg"));
}
catch (IOException nm)
{
System.out.println("begin");
System.out.println(nm.getMessage());
System.exit(0);
}
/******************************************
* Removes window framing. The next line sets fullscreen mode.
* Once fullscreen is set width and height are determined for the window
******************************************/
this.setUndecorated(true);
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
width = this.getWidth();
height = this.getHeight();
//Mouse click binding to slide advance control structure
addMouseListener(new Mouse());
//Create panel so that I can use key binding which requires JComponent
mainImagePanel = new PaintPanel();
add(mainImagePanel);
/******************************************
* Key Binding
* ESC will exit the slideshow
******************************************/
// Key bound AbstractAction items
escapeAction = new EscapeAction();
// Gets the mainImagePanel InputMap and pairs the key to the action
mainImagePanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "doEscapeAction");
// This line pairs the AbstractAction enterAction to the action "doEnterAction"
mainImagePanel.getActionMap().put("doEscapeAction", escapeAction);
/******************************************
* End Key Binding
******************************************/
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
SlideShow3 show = new SlideShow3();
show.setVisible(true);
}
});
}
//This method executes a specific SwingWorker class to preload images
public void start(String e)
{
if(e.equals("handCuffs"))
{
new ImageWorker(handCuffs.length, h, e).execute();
}
else if(e.equals("cups"))
{
new ImageWorker(cups.length, c, e).execute();
}
}
//Stretches and displays images in fullscreen window
private class PaintPanel extends JPanel
{
#Override
public void paintComponent(Graphics g)
{
if(screenImage != null)
{
super.paintComponent(g);
g.drawImage(screenImage, 0, 0, width, height, this);
}
}
}
/******************************************
* The following SwingWorker class Pre-loads all necessary images.
******************************************/
private class ArrayWrapper
{
private int i;
private Image image;
public ArrayWrapper(Image image, int i)
{
this.i = i;
this.image = image;
}
public int getIndex()
{
return i;
}
public Image getImage()
{
return image;
}
}
private class ImageWorker extends SwingWorker<Image[], ArrayWrapper>
{
private int currentPosition;
private int arraySize;
private String trickName;
private Image[] imageArray;
public ImageWorker(int arraySize, int currentPosition, String trick)
{
super();
this.currentPosition = currentPosition;
this.arraySize = arraySize;
this.trickName = trick;
}
#Override
public Image[] doInBackground()
{
imageArray = new Image[arraySize];
for(int i = currentPosition; i < currentPosition+40 && i < arraySize; i++)
{
try
{
imageArray[i] = ImageIO.read(new File("images/" + trickName + (i+1) + ".jpg"));
ArrayWrapper wrapArray = new ArrayWrapper(imageArray[i], i);
publish(wrapArray);
}
catch (IOException e)
{
System.out.println(trickName);
System.out.println(e.getMessage());
System.exit(0);
}
}
return imageArray;
}
#Override
public void process(List<ArrayWrapper> chunks)
{
for(ArrayWrapper element: chunks)
{
if(trickName.equals("handCuffs"))
{
handCuffs[element.getIndex()] = element.getImage();
}
else if(trickName.equals("cups"))
{
cups[element.getIndex()] = element.getImage();
}
}
}
#Override
public void done()
{
try
{
if(trickName.equals("handCuffs"))
{
handCuffs = get();
}
else if(trickName.equals("cups"))
{
cups = get();
}
}
catch(InterruptedException ignore){}
catch(java.util.concurrent.ExecutionException e)
{
String why = null;
Throwable cause = e.getCause();
if(cause != null)
{
why = cause.getMessage();
}
else
{
why = e.getMessage();
}
System.err.println("Error retrieving file: " + why);
}
}
}
/******************************************
* End SwingWorker Pre-Loading Classes
******************************************/
//Prints out time spent on each slide
public void timeStamp()
{
time1 = System.currentTimeMillis();
if(time0 != 0)
{
System.out.println(time1 - time0);
}
time0 = System.currentTimeMillis();
}
/******************************************
* User Input Classes for Key Binding Actions and Mouse Click Actions
******************************************/
private class EscapeAction extends AbstractAction
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public class Mouse extends MouseAdapter
{
#Override
public void mouseClicked(MouseEvent e)
{
if(!(h<handCuffs.length) && !(c<cups.length))
{
timeStamp();
System.exit(0);
}
else if(h<handCuffs.length)
{
timeStamp();
screenImage = handCuffs[h];
repaint();
System.out.print("handCuffs[" + (h+1) + "]\t");
h++;
//purge used slides and refresh slide buffer
if(h == 20 || h == 40)
{
for(int i = 0; i < h; i++)
{
handCuffs[i] = null;
}
start("handCuffs");
}
if(h == 45)
{
start("cups");
}
}
else if(c<cups.length)
{
timeStamp();
screenImage = cups[c];
repaint();
System.out.print("cups[" + (c+1) + "]\t");
c++;
//purge used slides and refresh slide buffer
if(c == 20 || c == 40 || c == 60 || c == 80 || c == 100 || c == 120 || c == 140 || c == 160)
{
for(int i = 0; i < c; i++)
{
cups[i] = null;
}
start("cups");
}
}
}
}
/******************************************
* End User Input Classes for Key Binding Actions and Mouse Click Actions
******************************************/
}
This example uses a List<ImageIcon> as a cache of images returned by getImage(). Using getResource(), the delay is imperceptible. The next and previous buttons are bound to the Space key by default.
Addendum: You can control navigation by conditioning a button's setEnabled() state using an instance of javax.swing.Timer, for example.
Addendum: Your second example waits until the mouse is clicked to begin reading an image, an indeterminate process that may return a copy immediately or may not complete until after repaint(). Instead, begin reading the images in the background using ImageIO.read(), as shown here. You can process() your List<Image> and show progress, as seen here. The SwingWorker can be launched from the initial thread, running while you subsequently build your GUI on the EDT. You can display the first image as soon as it is processed.