Memory Game score [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have created a memory game.
I am wanting to add a score system, so every time the player picks a matching pair they get a hit but if they don't they get a miss. It already has the basic function of a memory game, you pick a card, then another one and if they match they are both removed, if not they both turn back over again.
How do I go about displaying the current score? I have added 2 integer counters for a hit and a miss, but it doesn't seem to update.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class MemoryGame extends JFrame implements ActionListener {
private JFrame window = new JFrame("Memory Game");
private static final int WINDOW_WIDTH = 500; // pixels
private static final int WINDOW_HEIGHT = 500; // pixels
private JButton exitBtn, replayBtn, solveBtn;
ImageIcon ButtonIcon = createImageIcon("card.jpg");
private JButton[] gameBtn = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int Hit, Miss = 0;
private int counter = 0;
private int[] btnID = new int[2];
private int[] btnValue = new int[2];
private JLabel HitScore, MissScore;
private Panel gamePnl = new Panel();
private Panel buttonPnl = new Panel();
private Panel scorePnl = new Panel();
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = MemoryGame.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public MemoryGame()
{
createGUI();
createpanels();
setArrayListText();
window.setTitle("MemoryGame");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setVisible(true);
}
public void createGUI()
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i] = new JButton(ButtonIcon);
gameBtn[i].addActionListener(this);
}
HitScore = new JLabel("Hit: " + Hit);
MissScore = new JLabel("Miss: " + Miss);
exitBtn = new JButton("Exit");
exitBtn.addActionListener(this);
replayBtn = new JButton("Shuffle");
replayBtn.addActionListener(this);
solveBtn = new JButton("Solve");
solveBtn.addActionListener(this);
}
public void createpanels()
{
gamePnl.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
buttonPnl.add(replayBtn);
buttonPnl.add(exitBtn);
buttonPnl.add(solveBtn);
buttonPnl.setLayout(new GridLayout(1, 0));
scorePnl.add(HitScore);
scorePnl.add(MissScore);
scorePnl.setLayout(new GridLayout(1, 0));
window.add(scorePnl, BorderLayout.NORTH);
window.add(gamePnl, BorderLayout.CENTER);
window.add(buttonPnl, BorderLayout.SOUTH);
}
public void setArrayListText()
{
for (int i = 0; i < 2; i++)
{
for (int ii = 1; ii < (gameBtn.length / 2) + 1; ii++)
{
gameList.add(ii);
}
}
}
public boolean sameValues()
{
if (btnValue[0] == btnValue[1])
{
return true;
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if (exitBtn == e.getSource())
{
System.exit(0);
}
if (replayBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.remove(gameBtn[i]);
}
scorePnl.remove(HitScore);
scorePnl.remove(MissScore);
buttonPnl.remove(exitBtn);
buttonPnl.remove(replayBtn);
buttonPnl.remove(solveBtn);
window.remove(gamePnl);
window.remove(scorePnl);
window.remove(buttonPnl);
window.remove(window);
window.add(gamePnl);
window.add(scorePnl);
window.add(buttonPnl);
scorePnl.add(HitScore);
scorePnl.add(MissScore);
buttonPnl.add(exitBtn);
buttonPnl.add(replayBtn);
buttonPnl.add(solveBtn);
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
}
if (solveBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
}
}
for (int i = 0; i < gameBtn.length; i++)
{
if (gameBtn[i] == e.getSource())
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
gameBtn[btnID[0]].setVisible(false);
gameBtn[btnID[1]].setVisible(false);
Hit = Hit +1;
}
else
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
Miss = Miss +1;
}
counter = 1;
}
if (counter == 1)
{
btnID[0] = i;
btnValue[0] = gameList.get(i);
}
if (counter == 2)
{
btnID[1] = i;
btnValue[1] = gameList.get(i);
}
}
}
}
public static void main(String[] args)
{
new MemoryGame();
}
}

Maybe this will give you a push in the right direction. See especially the 5 new single line comments, one of which is a question.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class MemoryGame
// don't extend frame
/* extends JFrame */
implements ActionListener {
// very important!
public void updateHitMiss() {
HitScore.setText("Hit: " + Hit);
MissScore.setText("Miss: " + Miss);
}
private JFrame window = new JFrame("Memory Game");
private static final int WINDOW_WIDTH = 500; // pixels
private static final int WINDOW_HEIGHT = 500; // pixels
private JButton exitBtn, replayBtn, solveBtn;
ImageIcon ButtonIcon = createImageIcon("card.jpg");
private JButton[] gameBtn = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int Hit, Miss = 0;
private int counter = 0;
private int[] btnID = new int[2];
private int[] btnValue = new int[2];
private JLabel HitScore, MissScore;
// don't mix Swing with AWT
private JPanel gamePnl = new JPanel();
private JPanel buttonPnl = new JPanel();
private JPanel scorePnl = new JPanel();
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = MemoryGame.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public MemoryGame()
{
createGUI();
createJPanels();
setArrayListText();
window.setTitle("MemoryGame");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setVisible(true);
}
public void createGUI()
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i] = new JButton(ButtonIcon);
gameBtn[i].addActionListener(this);
}
HitScore = new JLabel("Hit: " + Hit);
MissScore = new JLabel("Miss: " + Miss);
exitBtn = new JButton("Exit");
exitBtn.addActionListener(this);
replayBtn = new JButton("Shuffle");
replayBtn.addActionListener(this);
solveBtn = new JButton("Solve");
solveBtn.addActionListener(this);
}
public void createJPanels()
{
gamePnl.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
buttonPnl.add(replayBtn);
buttonPnl.add(exitBtn);
buttonPnl.add(solveBtn);
buttonPnl.setLayout(new GridLayout(1, 0));
scorePnl.add(HitScore);
scorePnl.add(MissScore);
scorePnl.setLayout(new GridLayout(1, 0));
window.add(scorePnl, BorderLayout.NORTH);
window.add(gamePnl, BorderLayout.CENTER);
window.add(buttonPnl, BorderLayout.SOUTH);
}
public void setArrayListText()
{
for (int i = 0; i < 2; i++)
{
for (int ii = 1; ii < (gameBtn.length / 2) + 1; ii++)
{
gameList.add(ii);
}
}
}
public boolean sameValues()
{
if (btnValue[0] == btnValue[1])
{
return true;
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if (exitBtn == e.getSource())
{
System.exit(0);
}
if (replayBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.remove(gameBtn[i]);
}
// what was all this removing/adding intended to achieve?
/*
scorePnl.remove(HitScore);
scorePnl.remove(MissScore);
buttonPnl.remove(exitBtn);
buttonPnl.remove(replayBtn);
buttonPnl.remove(solveBtn);
window.remove(gamePnl);
window.remove(scorePnl);
window.remove(buttonPnl);
window.remove(window);
window.add(gamePnl);
window.add(scorePnl);
window.add(buttonPnl);
scorePnl.add(HitScore);
scorePnl.add(MissScore);
buttonPnl.add(exitBtn);
buttonPnl.add(replayBtn);
buttonPnl.add(solveBtn);
*/
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
}
if (solveBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
}
}
for (int i = 0; i < gameBtn.length; i++)
{
if (gameBtn[i] == e.getSource())
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
gameBtn[btnID[0]].setVisible(false);
gameBtn[btnID[1]].setVisible(false);
Hit = Hit +1;
}
else
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
Miss = Miss +1;
}
counter = 1;
}
if (counter == 1)
{
btnID[0] = i;
btnValue[0] = gameList.get(i);
}
if (counter == 2)
{
btnID[1] = i;
btnValue[1] = gameList.get(i);
}
}
}
updateHitMiss();
}
public static void main(String[] args)
{
// Swing GUIs should be created on the EDT
new MemoryGame();
}
}

Related

Can you add JButtons inside a JPanel

I'm making a Battleship game using one board. The picture below shows how the board GUI should look. My current code sets up a board without the 'menu-layer'. (see picture)
I tried doing this using Swing GUI designer in Intellij and got the following form (see picture), but can't find a way to insert these buttons inside the panel. Currently, I have got the following code.
package BattleshipGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BoardFrame extends JFrame {
//variables
Ships ship = new Ships();
static final Color colorHit = Color.red;
static final Color colorNormal = Color.gray;
static final Color colorWater = Color.blue;
static final Color colorCarrier = Color.yellow;
static final Color colorBattleship = Color.BLACK;
static final Color colorSubmarine = Color.magenta;
static final Color colorDestroyer = Color.white;
int[][] map;
private Container contents;
int cols;
int rows;
boolean equalPoints;
Player p1 = new Player();
Player p2 = new Player();
private JPanel mainPanel; // I tried using the GUI swing designer, but I cant manage to create
//a menu-layer on top of the buttons
private JButton buttonHighScores;
private JButton quitGame;
private JLabel player1Points;
private JLabel player2Points;
private JLabel playerTurn;
JButton[][] tiles = new JButton[100][100]; // I create 100*100 buttons, but only assign the right
// number to them
public void setMap(int[][] map) {
this.map = map;
}
public void SetFrame(int r, int c) {
this.rows = r;
this.cols = c;
}
public BoardFrame(int r, int c) {
super("Battleship");
setSize(400,450); // I create a frame
this.setLayout(new GridLayout(r, c)); // I set the layout depending on the number of rows and
//columns
AttackHandler attackHandler = new AttackHandler(); // action event class
p1.turn = true; // player 1's turn is true, he commences
p2.turn= false; //player 2's turn is false
for (int i =0; i<r; i++) {
for (int j =0; j <c; j++) {
tiles[i][j] = new JButton(); // this is where all the buttons are declared
tiles[i][j].setBackground(colorNormal);
add(tiles[i][j]);
tiles[i][j].addActionListener(attackHandler);
}
}
setResizable(true);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
setSize(400,450); //the size of my frame
}
public class AttackHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (source == tiles[i][j]) {
isHit(i, j);
return;
}
}
}
}
}
public void isHit(int row, int col) {
// the map consists of an 2D array
//where 0's represent the water, 1's represent the tiles that are
//already hit, and the other represent the ships
if (AllHit()) {
JOptionPane.showMessageDialog(null, "All Ships Destructed!");
setWinner();
String winner =DecideWinner();
JOptionPane.showMessageDialog(null, winner+" has won!", "Winner",
JOptionPane.PLAIN_MESSAGE);
int again = JOptionPane.showConfirmDialog(null, "Play Again", "Play
Again",JOptionPane.YES_NO_OPTION);
if (again==0){
Main.main(null);
}
dispose();
}
else if (map[row][col] == 5) {
AddPoint(p1.turn, 5); // this should add points to the player that
//has the turn
tiles[row][col].setBackground(colorCarrier);
map[row][col] = 1;
} else if (map[row][col] == 4) {
AddPoint(p1.turn, 4);
tiles[row][col].setBackground(colorBattleship);
map[row][col] = 1;
} else if (map[row][col] == 3) {
AddPoint(p1.turn, 3);
tiles[row][col].setBackground(colorSubmarine);
map[row][col] = 1;
} else if (map[row][col] == 2) {
AddPoint(p1.turn, 2);
tiles[row][col].setBackground(colorDestroyer);
map[row][col] = 1;
} else if (map[row][col] == 1) {
System.out.println("Already Hit!");
} else if (map[row][col] == 0 || map[row][col] == 9) {
tiles[row][col].setBackground(colorWater);
map[row][col] = 1;
}
p1.changeTurn(p1.turn); // every click, the turn of each player should
//switch from true to false, p1 starts with value
//true, and p2 with false
p2.changeTurn(p2.turn);
System.out.println("Points Player 1: "+p1.points);
System.out.println("Points Player 2: "+p2.points);
}
public boolean AllHit() { // if all ships are hit, a message pops up
boolean allHit = true;
for (int i = 0; i<rows;i++) {
for (int j = 0; j < cols; j++) {
if (map[i][j] != 1 && map[i][j] != 0) {
allHit = false;
break;
}
}
}
return allHit;
}
public void AddRandomShips(int rows, int cols) {
int[][] map = ship.setRandomShips(rows, cols);
setMap(map);
}
public void AddShipsNotRandom(int size, int[][] coordinates){
int[][] map = ship.PlaceShips(size, coordinates);
setMap(map);
}
public void ScoreMethod(boolean scoreMethod){
if(scoreMethod){
equalPoints = true;
}
else if(!scoreMethod){ // the second method adjusts the score
//for the second player because the first player
//is more likely to hit a ship
equalPoints = false;
}
}
public void AddPoint(boolean turn,int amount){
if (turn){
p1.points = p1.points+ amount;
}
else p2.points = p2.points+amount;
}
public void setWinner(){
if(p1.points>p2.points){
p1.setWon();
}
else p2.setWon();
}
public String DecideWinner(){
if (p1.won == true){
return "Player 1";
}
else return "Player 2";
}
}
This is how the GUI should look like:
This is what my code generates:
this is the for that I designed using Intellij's Swing Designer (the panel with 'buttons' should be filled with the JButtons I created in the code):
UPDATE :
Thanks to mr. Kroukamp, I was able to add a menu-overlay. The code looks like this:
package BattleshipGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Dimension;
public class BoardFrame extends JFrame {
//variables
Ships ship = new Ships();
static final Color colorNormal = Color.gray;
static final Color colorWater = Color.blue;
static final Color colorCarrier = Color.yellow;
static final Color colorBattleship = Color.BLACK;
static final Color colorSubmarine = Color.magenta;
static final Color colorDestroyer = Color.white;
int[][] map;
int cols;
int rows;
boolean equalPoints;
Player p1 = new Player();
Player p2 = new Player();
JButton[][] tiles = new JButton[100][100];
public void setMap(int[][] map) {
this.map = map;
}
public void SetFrame(int r, int c) {
this.rows = r;
this.cols = c;
}
JButton highScoresButton = new JButton("High Scores");
JLabel player1ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JLabel turnTitleLabel = new JLabel(Turn());
JLabel player2ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JButton quitGameButton = new JButton("Quite Game");
JFrame frame = new JFrame("Battleship");
public BoardFrame(int r, int c) {
super("Battleship");
AttackHandler attackHandler = new AttackHandler(); // action event class
p1.turn = true; // player 1's turn is true, he commences
p2.turn= false; //player 2's turn is false
JFrame frame = new JFrame("Battleship");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// panel 1 (yellow border)
JPanel panel1 = new JPanel(new GridBagLayout());
JButton highScoresButton = new JButton("High Scores");
JLabel player1ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JLabel turnTitleLabel = new JLabel(Turn());
JLabel player2ScoreTitleLabel = new JLabel(String.valueOf(p1.points));
JButton quitGameButton = new JButton("Quite Game");
GridBagConstraints s = new GridBagConstraints();
s.weightx = 1;
s.gridx = 0;
s.gridy = 0;
panel1.add(highScoresButton, s);
s.weightx = 1;
s.gridx = 1;
s.gridy = 0;
panel1.add(player1ScoreTitleLabel, s);
s.weightx = 1;
s.gridx = 2;
s.gridy = 0;
panel1.add(turnTitleLabel);
s.weightx = 1;
s.gridx = 3;
s.gridy = 0;
panel1.add(player2ScoreTitleLabel, s);
s.weightx = 1;
s.gridx = 4;
s.gridy = 0;
panel1.add(quitGameButton, s);
// panel 2 (red border)
JPanel panel2 = new JPanel();
GridLayout layout = new GridLayout(r, c);
layout.setHgap(0);
layout.setVgap(0);
panel2.setLayout(layout);
panel2.setBorder(new LineBorder(Color.blue, 4));
for (int i =0; i<r; i++) {
for (int j =0; j < c; j++) {
tiles[i][j] = new JButton(){
#Override
public Dimension getPreferredSize() {
return new Dimension(100,100);
}
};
tiles[i][j].setBackground(colorNormal);
panel2.add(tiles[i][j]);
tiles[i][j].addActionListener(attackHandler);
}
}
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public class AttackHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (source == tiles[i][j]) {
isHit(i, j);
return;
}
}
}
}
}
public void isHit(int row, int col) {
if (AllHit()) {
JOptionPane.showMessageDialog(null, "All Ships Destructed!");
setWinner();
String winner =DecideWinner();
if(p1.won){
p1.checkHighScore();
}
else if (p2.won){
p2.checkHighScore();
}
JOptionPane.showMessageDialog(null, winner, "Winner",
JOptionPane.PLAIN_MESSAGE);
int again = JOptionPane.showConfirmDialog(null, "Play Again", "Play
Again",JOptionPane.YES_NO_OPTION);
if (again==0){
Main.main(null);
}
frame.dispose();
}
else if (map[row][col] == 5) {
AddPoint(p1.turn, 5);
tiles[row][col].setBackground(colorCarrier);
map[row][col] = 1;
} else if (map[row][col] == 4) {
AddPoint(p1.turn, 4);
tiles[row][col].setBackground(colorBattleship);
map[row][col] = 1;
} else if (map[row][col] == 3) {
AddPoint(p1.turn, 3);
tiles[row][col].setBackground(colorSubmarine);
map[row][col] = 1;
} else if (map[row][col] == 2) {
AddPoint(p1.turn, 2);
tiles[row][col].setBackground(colorDestroyer);
map[row][col] = 1;
} else if (map[row][col] == 1) {
System.out.println("Already Hit!");
} else if (map[row][col] == 0 || map[row][col] == 9) {
tiles[row][col].setBackground(colorWater);
map[row][col] = 1;
}
p1.changeTurn(p1.turn);
p2.changeTurn(p2.turn);
// I cannot find a way to change the labels....
player1ScoreTitleLabel.setText(String.valueOf(p1.points));
player2ScoreTitleLabel.setText(String.valueOf(p2.points));
turnTitleLabel.setText(Turn());
System.out.println("Points Player 1: "+p1.points);
System.out.println("Points Player 2: "+p2.points);
}
public boolean AllHit() {
boolean allHit = true;
for (int i = 0; i<rows;i++) {
for (int j = 0; j < cols; j++) {
if (map[i][j] != 1 && map[i][j] != 0) {
allHit = false;
break;
}
}
}
return allHit;
}
public void AddRandomShips(int rows, int cols) {
int[][] map = ship.setRandomShips(rows, cols);
setMap(map);
}
public void AddShipsNotRandom(int size, int[][] coordinates){
int[][] map = ship.PlaceShips(size, coordinates);
setMap(map);
}
public void ScoreMethod(boolean scoreMethod){
if(scoreMethod){
equalPoints = true;
}
else {
equalPoints = false;
}
}
public void AddPoint(boolean turn,int amount){
if (turn){
p1.points = p1.points+ amount;
}
else p2.points = p2.points+amount;
}
public void setWinner(){
if(p1.points>p2.points){
p1.setWon();
}
else if (p2.points>p1.points){
p2.setWon();
}
}
public String DecideWinner(){
if (p1.won){
return "Player 1 won the game!";
}
else if (p2.won){
return "Player 2 won the game!";
}
else return "It's a tie!";
}
public String Turn(){
if (p1.turn){
return "Player 1";
}else return "Player 2";
}
This generates the following GUI:
However, I am still struggling finding a way to change the values of the text of the score JLabels, the following code did not work for me:
player1ScoreTitleLabel.setText(String.valueOf(p1.points));
player2ScoreTitleLabel.setText(String.valueOf(p2.points));
turnTitleLabel.setText(Turn())
Adding to my comment here is a small example to help get you started without the burden of an IDE for building your UI incorporating as much of Swing best practices as possible:
I opted to use JLabels as it just makes more sense
The yellow border represents panel1 which makes use of a GridBagLayout.
The red panel represents panel2 which makes use of a GridLayout.
Finally the 2 JPanels are added to a JFrame which by default uses BorderLayout.
TestApp.java:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class TestApp {
public TestApp() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGui() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// panel 1 (yellow border)
JPanel panel1 = new JPanel(new GridBagLayout());
JButton highScoresButton = new JButton("High Scores");
JLabel player1ScoreLabel = new JLabel("<html>Player 1 Score:<br><h2>950</h2>");
JLabel turnLabel = new JLabel("<html>Turn:<br><h1>Player 1</h1>");
JLabel player2ScoreLabel = new JLabel("<html>Player 2 Score:<br><h2>925</h2>");
JButton quitGameButton = new JButton("Quit Game");
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.gridx = 0;
c.gridy = 0;
panel1.add(highScoresButton, c);
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
panel1.add(player1ScoreLabel, c);
c.weightx = 1;
c.gridx = 2;
c.gridy = 0;
panel1.add(turnLabel);
c.weightx = 1;
c.gridx = 3;
c.gridy = 0;
panel1.add(player2ScoreLabel, c);
c.weightx = 1;
c.gridx = 4;
c.gridy = 0;
panel1.add(quitGameButton, c);
panel1.setBorder(new LineBorder(Color.YELLOW, 4)); // just for visual purposes of the answer
// panel 2 (red border)
JPanel panel2 = new JPanel();
GridLayout layout = new GridLayout(8, 8);
layout.setHgap(5);
layout.setVgap(5);
panel2.setLayout(layout);
panel2.setBorder(new LineBorder(Color.RED, 4)); // just for visual purposes of the answer
for (int i = 0; i < 64; i++) {
JLabel label = new JLabel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
label.setOpaque(true);
label.setBackground(Color.DARK_GRAY);
panel2.add(label);
}
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}

How to get the true x and y coordinates of a JTextField

I had an issue with a piece of code I was writing where I was adding JPanel's inside of others to form a layout. The issue is that after the window is displayed I needed to get the x and y coordinates of one of the text fields but whenever I try using the getX() and getY() methods they keep returning 0. I have verified that the getX() and getY() methods are being called after the window is initialized and displayed. How can I fix this and get the actual coordinates of the text field.
This is window code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class GraphicsPanel extends JFrame implements ActionListener, CaretListener{
JPanel buttonPanel = new JPanel();
JPanel mainPanel = new JPanel();
JPanel animationPanel = new JPanel();
JPanel bottomPanel = new JPanel();
JPanel text = new JPanel();
PokemonLearnsets info = new PokemonLearnsets();
HealthBar healthBar1 = new HealthBar();
HealthBar healthBar2 = new HealthBar();
JTextArea textArea = new JTextArea();
JTextField response = new JTextField();
int health1 = 100;
int total1 = 100;
int health2 = 100;
int total2 = 100;
int startOfRect = 1;
int p1MonNum = -1;
int waitTime = 20;
int p2MonNum = -1;
TextInterface theText;
Icon allIcons[][];
JLabel p1Gif;
JLabel p2Gif;
JPanel mainBuilderPanel = new JPanel();
JPanel builderPanel = new JPanel();
JPanel builderMessagePanel = new JPanel();
JPanel monPanels [] = new JPanel[6];
JPanel imagePanels[] = new JPanel[6];
JPanel namePanels[] = new JPanel[6];
JPanel movePanels[] = new JPanel[6];
JPanel allMoves[][] = new JPanel[6][4];
JTextField names[] = new JTextField[6];
JTextField moves[][] = new JTextField[6][4];
JButton validate = new JButton("Validate");
JLabel tempImages[] = new JLabel[6];
JLabel emptyLabels[] = new JLabel[6];
AutoSuggestor [] nameSuggestions = new AutoSuggestor[6];
AutoSuggestor [][] moveSuggestions = new AutoSuggestor[6][4];
public GraphicsPanel(String name){
super(name);
setupTeamBuilderPanel();
// setupBattlePanel();
}
private void setupTeamBuilderPanel() {
Container c = getContentPane();
mainBuilderPanel.setLayout(new BorderLayout());
mainBuilderPanel.setBorder(new LineBorder(Color.BLACK, 2));
builderPanel.setLayout(new GridLayout(1, 0));
builderPanel.setBorder(new LineBorder(Color.BLACK, 1));
builderMessagePanel.setBorder(new LineBorder(Color.BLACK, 2));
for (int i = 0; i < monPanels.length; i ++) {
monPanels[i] = new JPanel();
imagePanels[i] = new JPanel();
namePanels[i] = new JPanel();
movePanels[i] = new JPanel();
names[i] = new JTextField();
names[i].addCaretListener(this);
emptyLabels[i] = new JLabel();
tempImages[i] = emptyLabels[i];
monPanels[i].setBorder(new LineBorder(Color.BLACK, 3));
imagePanels[i].setBorder(new LineBorder(Color.BLACK, 3));
movePanels[i].setBorder(new LineBorder(Color.BLACK, 3));
monPanels[i].setLayout(new GridLayout(0 ,1));
namePanels[i].setLayout(new GridLayout(1, 0));
movePanels[i].setLayout(new GridLayout(0, 1));
imagePanels[i].setLayout(new BorderLayout());
namePanels[i].add(new JLabel(" Name:"));
namePanels[i].add(names[i]);
imagePanels[i].add(tempImages[i]);
imagePanels[i].add(namePanels[i], BorderLayout.SOUTH);
monPanels[i].add(imagePanels[i]);
for (int k = 0; k < moves[i].length; k ++) {
moves[i][k] = new JTextField();
allMoves[i][k] = new JPanel();
allMoves[i][k].setLayout(new GridLayout(0, 1));
allMoves[i][k].add(new JLabel(" Move " + Integer.toString(k + 1) + ":"));
allMoves[i][k].add(moves[i][k]);
allMoves[i][k].add(new JLabel());
allMoves[i][k].add(new JLabel());
movePanels[i].add(allMoves[i][k]);
}
monPanels[i].add(movePanels[i]);
builderPanel.add(monPanels[i]);
}
String welcomeMessage = "";
for (int i = 0; i < 5; i ++) {
welcomeMessage += " ";
}
welcomeMessage += "Welcome to the Teambuilder!";
setupSuggestions();
validate.addActionListener(this);
builderMessagePanel.add(new JLabel(welcomeMessage));
mainBuilderPanel.add(builderMessagePanel, BorderLayout.NORTH);
mainBuilderPanel.add(validate, BorderLayout.SOUTH);
mainBuilderPanel.add(builderPanel);
c.add(mainBuilderPanel);
}
private void setupBattlePanel() {
Container c = getContentPane();
mainPanel.setLayout(new GridLayout());
bottomPanel.setLayout(new GridLayout());
animationPanel.setBorder(new LineBorder(Color.BLACK, 3));
animationPanel.setLayout(new GridLayout(0, 2));
mainPanel.add(animationPanel);
buttonPanel.setBorder(new LineBorder(Color.BLACK, 3));
buttonPanel.setLayout(new FlowLayout(5));
buttonPanel.setBackground(Color.GREEN);
// buttonPanel.add(new JLabel(" "));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
bottomPanel.add(buttonPanel);
text.setLayout(new GridLayout());
text.setBorder(new LineBorder(Color.BLACK, 3));
text.add(response);
bottomPanel.add(text);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setBackground(Color.LIGHT_GRAY);
JScrollPane textAreaPane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
textAreaPane.setBorder(new LineBorder(Color.BLACK, 3));
mainPanel.add(textAreaPane);
c.add(mainPanel, BorderLayout.CENTER);
c.add(bottomPanel, BorderLayout.SOUTH);
}
private void setupSuggestions() {
ArrayList<String> allPossibleMoves = new ArrayList<String>();
Collections.addAll(allPossibleMoves, info.getAllMoves());
for (int i = 0; i < 6; i ++) {
for (int k = 0; k < 4; k ++) {
moveSuggestions[i][k] = new AutoSuggestor(moves[i][k], allPossibleMoves, Color.WHITE.brighter(), Color.BLACK, Color.BLACK, 0.75f);
moveSuggestions[i][k].setTextField(moves[i][k]);
}
}
}
public void writeToScreen(String writing) {
String current = textArea.getText();
textArea.setText(current + writing);
}
public void updateAll() {
mainPanel.updateUI();
bottomPanel.updateUI();
mainBuilderPanel.updateUI();
}
public void setTextInterface(TextInterface text) {
theText = text;
response.addActionListener(theText.action);
}
public void drawMons(String name1, String name2) {
animationPanel.removeAll();
ImageIcon secImage = new ImageIcon(this.getClass().getResource("SpritesFront/" + name2 + ".gif"));
secImage = new ImageIcon(secImage.getImage().getScaledInstance((int)(secImage.getIconWidth() * 1.5), (int)(secImage.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon = secImage;
p2Gif = new JLabel(icon);
ImageIcon firstImage = new ImageIcon(this.getClass().getResource("SpritesBack/" + name1 + "-back.gif"));
firstImage = new ImageIcon(firstImage.getImage().getScaledInstance((int)(firstImage.getIconWidth() * 1.5), (int)(firstImage.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon2 = firstImage;
p1Gif = new JLabel(icon2);
animationPanel.add(healthBar2);
animationPanel.add(p2Gif);
animationPanel.add(p1Gif);
animationPanel.add(healthBar1);
updateAll();
}
public void fillPortions(int x) {
JLabel [] labels = new JLabel[x];
for (int i = 0; i < x; i ++) {
labels[i] = new JLabel();
animationPanel.add(labels[i]);
}
}
public void refreshHealthBar(int health, int total, int pNum, int mon) {
if (pNum == 1) {
if (p1MonNum != mon && p1MonNum != -1) {
p1MonNum = mon;
health1 = health;
total1 = total;
healthBar1.setHealth(health);
healthBar1.setTotal(total);
redoHealthPanel();
}
else {
p1MonNum = mon;
healthBar1.setTotal(total);;
while (health < health1) {
healthBar1.setHealth(health1);
redoHealthPanel();
health1--;
}
while (health > health1) {
healthBar1.setHealth(health1);
redoHealthPanel();
health1++;
}
}
}
else {
if (p2MonNum != mon && p2MonNum != -1) {
p2MonNum = mon;
health2 = health;
total2 = total;
healthBar2.setHealth(health);
healthBar2.setTotal(total);
redoHealthPanel();
updateAll();
}
else {
p2MonNum = mon;
healthBar2.setTotal(total);
while (health < health2) {
healthBar2.setHealth(health2);
redoHealthPanel();
health2--;
}
while (health > health2) {
healthBar2.setHealth(health2);
redoHealthPanel();
health2++;
}
}
}
}
private void redoHealthPanel () {
animationPanel.removeAll();
animationPanel.add(healthBar2);
animationPanel.add(p2Gif);
animationPanel.add(p1Gif);
animationPanel.add(healthBar1);
updateAll();
try {
TimeUnit.MILLISECONDS.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private String validatePokemon() {
String answer = "";
String tempMonNames [] = new String[6];
boolean invalidMove = false;
for (int i = 0; i < monPanels.length; i ++) {
String currentName = names[i].getText();
if (currentName.isEmpty()) {
answer = "You must have 6 Pokemon on your team but you can have less than 4 moves";
return answer;
}
for (String element : tempMonNames) {
if (element == null) {
continue;
} else if (currentName.equals(element)) {
answer = "You have duplicate Pokemon on your team";
return answer;
}
}
if (!info.validPokemon(currentName)) {
answer += "Pokemon #" + (i + 1) + " is invalid\n";
} else {
tempMonNames[i] = currentName;
}
int count = 0;
for (int k = 0; k < moves[i].length; k++) {
if (moves[i][k].getText().isEmpty()) {
count++;
}
if (!info.validMove(moves[i][k].getText().replace(" ", "").toLowerCase(), currentName)) {
answer += "Pokemon #" + (i + 1) + ", move #" + (k + 1) + " is invalid\n";
invalidMove = true;
}
if (count >= 4) {
answer += "Pokemon #" + (i + 1) + " has no moves\n";
break;
}
}
}
if (invalidMove) {
answer += "***Please keep in mind only damaging moves without recoil are allowed, if there aren't enough for 4 moves, leave fields blank***";
}
return answer;
}
#Override
public void actionPerformed(ActionEvent e) {
if (validatePokemon().isEmpty()) {
JOptionPane.showMessageDialog(null, "Confirmed" , "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, validatePokemon() , "", JOptionPane.ERROR_MESSAGE);
}
}
#Override
public void caretUpdate(CaretEvent e) {
for (int i = 0; i < names.length; i ++) {
if (info.validPokemon(names[i].getText()) && tempImages[i].getParent() == null) {
ImageIcon temp = new ImageIcon(this.getClass().getResource("SpritesFront/" + names[i].getText().replace(" ", "").replace(":", "").replace("'", "").replace(".", "").replace("-", "").toLowerCase() + ".gif"));
temp = new ImageIcon(temp.getImage().getScaledInstance((int)(temp.getIconWidth() * 1.5), (int)(temp.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon = temp;
imagePanels[i].remove(tempImages[i]);
tempImages[i] = new JLabel(icon);
imagePanels[i].add(tempImages[i]);
updateAll();
} else if (!info.validPokemon(names[i].getText())){
imagePanels[i].remove(tempImages[i]);
updateAll();
}
}
}
}
This is set up for the window:
GraphicsPanel window = new GraphicsPanel("Pokemon");
window.setBounds(0, 0, 1440, 830);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
This is where the getX() and getY() are getting called:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class AutoSuggestor {
private final JTextComponent textComp;
private JPanel suggestionsPanel;
private JWindow autoSuggestionPopUpWindow;
private String typedWord;
private final ArrayList<String> dictionary = new ArrayList<>();
private JTextField textField;
private int currentIndexOfSpace, tW, tH;
private DocumentListener documentListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
#Override
public void removeUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
#Override
public void changedUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
};
private final Color suggestionsTextColor;
private final Color suggestionFocusedColor;
public AutoSuggestor(JTextComponent textComp, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
this.textComp = textComp;
this.suggestionsTextColor = textColor;
this.suggestionFocusedColor = suggestionFocusedColor;
this.textComp.getDocument().addDocumentListener(documentListener);
setDictionary(words);
typedWord = "";
currentIndexOfSpace = 0;
tW = 0;
tH = 0;
autoSuggestionPopUpWindow = new JWindow();
autoSuggestionPopUpWindow.setOpacity(opacity);
suggestionsPanel = new JPanel();
suggestionsPanel.setLayout(new GridLayout(0, 1));
suggestionsPanel.setBackground(popUpBackground);
addKeyBindingToRequestFocusInPopUpWindow();
}
private void addKeyBindingToRequestFocusInPopUpWindow() {
textComp.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
textComp.getActionMap().put("Down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
break;
}
}
}
});
suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {
int lastFocusableIndex = 0;
#Override
public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))
ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
int max = sls.size();
if (max > 1) {//more than 1 suggestion
for (int i = 0; i < max; i++) {
SuggestionLabel sl = sls.get(i);
if (sl.isFocused()) {
if (lastFocusableIndex == max - 1) {
lastFocusableIndex = 0;
sl.setFocused(false);
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
} else {
sl.setFocused(false);
lastFocusableIndex = i;
}
} else if (lastFocusableIndex <= i) {
if (i < max) {
sl.setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
lastFocusableIndex = i;
break;
}
}
}
} else {//only a single suggestion was given
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
}
}
});
}
private void setFocusToTextField() {
textComp.requestFocusInWindow();
}
public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
ArrayList<SuggestionLabel> sls = new ArrayList<>();
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
sls.add(sl);
}
}
return sls;
}
private void checkForAndShowSuggestions() {
typedWord = getCurrentlyTypedWord();
suggestionsPanel.removeAll();//remove previos words/jlabels that were added
//used to calcualte size of JWindow as new Jlabels are added
tW = 0;
tH = 0;
boolean added = wordTyped(typedWord);
if (!added) {
if (autoSuggestionPopUpWindow.isVisible()) {
autoSuggestionPopUpWindow.setVisible(false);
}
} else {
showPopUpWindow();
setFocusToTextField();
}
}
protected void addWordToSuggestions(String word) {
SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);
calculatePopUpWindowSize(suggestionLabel);
suggestionsPanel.add(suggestionLabel);
}
public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
String text = textComp.getText();
String wordBeingTyped = "";
text = text.replaceAll("(\\r|\\n)", " ");
if (text.contains(" ")) {
int tmp = text.lastIndexOf(" ");
if (tmp >= currentIndexOfSpace) {
currentIndexOfSpace = tmp;
wordBeingTyped = text.substring(text.lastIndexOf(" "));
}
} else {
wordBeingTyped = text;
}
return wordBeingTyped.trim();
}
private void calculatePopUpWindowSize(JLabel label) {
//so we can size the JWindow correctly
if (tW < label.getPreferredSize().width) {
tW = label.getPreferredSize().width;
}
tH += label.getPreferredSize().height;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
private void showPopUpWindow() {
autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.setSize(tW, tH);
autoSuggestionPopUpWindow.setVisible(true);
//show the pop up
autoSuggestionPopUpWindow.setLocation(textComp.getX(), textComp.getY() + textComp.getHeight());
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.revalidate();
autoSuggestionPopUpWindow.repaint();
}
public void setDictionary(ArrayList<String> words) {
dictionary.clear();
if (words == null) {
return;//so we can call constructor with null value for dictionary without exception thrown
}
for (String word : words) {
dictionary.add(word);
}
}
public JWindow getAutoSuggestionPopUpWindow() {
return autoSuggestionPopUpWindow;
}
public JTextComponent getTextField() {
return textComp;
}
public void addToDictionary(String word) {
dictionary.add(word);
}
boolean wordTyped(String typedWord) {
if (typedWord.isEmpty()) {
return false;
}
//System.out.println("Typed word: " + typedWord);
boolean suggestionAdded = false;
for (String word : dictionary) {//get words in the dictionary which we added
boolean fullymatches = true;
for (int i = 0; i < typedWord.length(); i++) {//each string in the word
if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
fullymatches = false;
break;
}
}
if (fullymatches) {
addWordToSuggestions(word);
suggestionAdded = true;
}
}
return suggestionAdded;
}
}
class SuggestionLabel extends JLabel {
private boolean focused = false;
private final JWindow autoSuggestionsPopUpWindow;
private final JTextComponent textComponent;
private final AutoSuggestor autoSuggestor;
private Color suggestionsTextColor, suggestionBorderColor;
public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
super(string);
this.suggestionsTextColor = suggestionsTextColor;
this.autoSuggestor = autoSuggestor;
this.textComponent = autoSuggestor.getTextField();
this.suggestionBorderColor = borderColor;
this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();
initComponent();
}
private void initComponent() {
setFocusable(true);
setForeground(suggestionsTextColor);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
getActionMap().put("Enter released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
}
public void setFocused(boolean focused) {
if (focused) {
setBorder(new LineBorder(suggestionBorderColor));
} else {
setBorder(null);
}
repaint();
this.focused = focused;
}
public boolean isFocused() {
return focused;
}
private void replaceWithSuggestedText() {
String suggestedWord = getText();
String text = textComponent.getText();
String typedWord = autoSuggestor.getCurrentlyTypedWord();
String t = text.substring(0, text.lastIndexOf(typedWord));
String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
textComponent.setText(tmp);
}
}
The textComp.getX() and textComp.getY() in the showPopUpWindow method are the ones that are giving zeros.
After thinking about it for a while I came up with this solution and it works for me.
int x = 0;
int y = 0;
Component currentComponent = textComp;
while (currentComponent != null) {
x += currentComponent.getX();
y += currentComponent.getY();
currentComponent = currentComponent.getParent();
}

Creating a counter for bubblesort

I'm trying to make a counter that counts up every time a number is swapped. I think I'm on the right track, but my counter doesn't show, however, it compiles and runs okay. This code sorts all the numbers from smallest to largest and I need to count up how many times it swaps.
It needs to be placed in the bubblesort() method. I believe you would have to add swapItems to +1 to counter every time it makes a move. If someone could help me here that would be much appreciated.
The code that has ">" on the left side of it is the counter part of the code.
// Sorting Application
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sort2 extends JFrame implements ActionListener{
private TextField[] items = new TextField[6];
private JButton btnSort, btnClear, btnReset;
private TextField tmp;
private Label status;
private int pauseInterval = 100; // ms
public static void main(String[] args) {
new Sort2().setVisible(true);
}
public Sort2() {
init();
}
public void init() {
setTitle("Sorting Algorithms");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(440, 200);
JPanel jp = new JPanel(new BorderLayout());
jp.setPreferredSize(new Dimension(440, 200));
jp.setBackground(Color.white);
JPanel itemPanel = new JPanel();
itemPanel.setBackground(Color.white);
for (int i = 0; i < items.length; i++) {
items[i] = new TextField(3);
items[i].setPreferredSize(new Dimension(30,40));
itemPanel.add(items[i]);
}
initItems();
itemPanel.add(new Label("Temp:"));
tmp = new TextField(4);
tmp.setPreferredSize(new Dimension(30,40));
tmp.setEditable(false);
itemPanel.add(tmp);
itemPanel.add(new Label(""))
.setPreferredSize(new Dimension(380, 65));
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
btnSort = new JButton("Sort");
btnReset = new JButton("Reset");
btnClear = new JButton("Clear");
btnSort.addActionListener(this);
btnClear.addActionListener(this);
btnReset.addActionListener(this);
buttonPanel.add(btnSort);
buttonPanel.add(btnClear);
buttonPanel.add(btnReset);
status = new Label("Wating ... ");
status.setPreferredSize(new Dimension(380, 40));
JPanel statusPanel = new JPanel();
statusPanel.setBackground(Color.white);
statusPanel.add(status, BorderLayout.SOUTH);
jp.add(itemPanel, BorderLayout.NORTH);
jp.add(buttonPanel, BorderLayout.CENTER);
jp.add(statusPanel, BorderLayout.SOUTH);
getContentPane().add(jp);
}
private void initItems() {
for (int i = 0; i < items.length; i++) {
items[i].setText((
String.valueOf((int)(Math.random()*100))));
}
}
private void pause(int ms) {
try {
Thread.sleep(ms);
}
catch (InterruptedException e) {
showStatus(e.toString());
}
}
private void assign(TextField to, TextField from) {
Color tobg = to.getBackground();
to.setBackground(Color.green);
pause(pauseInterval);
to.setText(from.getText());
pause(pauseInterval);
to.setBackground(tobg);
}
private void swapItems(TextField t1, TextField t2) {
assign(tmp,t1);
assign(t1,t2);
assign(t2,tmp);
}
private boolean greaterThan(TextField t1, TextField t2) {
boolean greater;
Color t1bg = t1.getBackground();
Color t2bg = t2.getBackground();
t1.setBackground(Color.cyan);
t2.setBackground(Color.cyan);
pause(pauseInterval);
greater = Integer.parseInt(t1.getText()) <
Integer.parseInt(t2.getText());
pause(pauseInterval);
t1.setBackground(t1bg);
t2.setBackground(t2bg);
return greater;
}
> private void bubbleSort() {
> int currentCount = 0;
> showStatus("Sorting ...");
> boolean swap = true;
> while (swap) {
> swap=false;
> for (int i = 0; i < items.length-1; i++) {
> if (greaterThan(items[i],items[i+1])) {
> swapItems(items[i],items[i+1]);
> swap=true;
> for (int step = 1; step <= items.length+1; step++) {
> currentCount = currentCount + 1;
> }
> }
> } //for
> } // while
> showStatus("Sort complete" + " number of swaps = " + currentCount);
> } // bubbleSort
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "Clear":
for (int i = 0; i < items.length; i++) {
items[i].setText("");
}
break;
case "Sort":
bubbleSort();
break;
case "Reset":
initItems();
break;
default:
showStatus("Unrecognised button: " + e.toString());
}
}
private void showStatus(String s) {
status.setText(s);
}
}
Please find the updated working code which count the swapping.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Counter extends JFrame implements ActionListener {
private TextField[] items = new TextField[6];
private JButton btnSort, btnClear, btnReset;
private TextField tmp;
private Label status;
private JLabel cntLabel;
private int pauseInterval = 100;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
Counter f = new Counter();
f.init();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public Counter() {
// init();
}
public void init() {
setTitle("Sorting Algorithms");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(440, 200);
JPanel jp = new JPanel(new BorderLayout());
jp.setPreferredSize(new Dimension(440, 200));
jp.setBackground(Color.white);
JPanel itemPanel = new JPanel(new FlowLayout());
itemPanel.setBackground(Color.white);
for (int i = 0; i < items.length; i++) {
items[i] = new TextField(3);
items[i].setPreferredSize(new Dimension(30, 40));
itemPanel.add(items[i]);
}
initItems();
itemPanel.add(new Label("Temp:"));
tmp = new TextField(4);
tmp.setPreferredSize(new Dimension(30, 40));
tmp.setEditable(false);
itemPanel.add(tmp);
itemPanel.add(cntLabel).setPreferredSize(new Dimension(100, 65));
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
btnSort = new JButton("Sort");
btnReset = new JButton("Reset");
btnClear = new JButton("Clear");
btnSort.addActionListener(this);
btnClear.addActionListener(this);
btnReset.addActionListener(this);
buttonPanel.add(btnSort);
buttonPanel.add(btnClear);
buttonPanel.add(btnReset);
status = new Label("Wating ... ");
status.setPreferredSize(new Dimension(380, 40));
JPanel statusPanel = new JPanel();
statusPanel.setBackground(Color.white);
statusPanel.add(status, BorderLayout.SOUTH);
jp.add(itemPanel, BorderLayout.NORTH);
jp.add(buttonPanel, BorderLayout.CENTER);
jp.add(statusPanel, BorderLayout.SOUTH);
getContentPane().add(jp);
}
private void initItems() {
for (int i = 0; i < items.length; i++) {
items[i].setText((String.valueOf((int) (Math.random() * 100))));
}
// if(null!=swapLabel)
// swapLabel.setText("");
cntLabel = new JLabel("0");
}
private void pause(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
showStatus(e.toString());
}
}
private void assign(TextField to, TextField from) {
Color tobg = to.getBackground();
to.setBackground(Color.green);
pause(pauseInterval);
to.setText(from.getText());
pause(pauseInterval);
to.setBackground(tobg);
}
private void swapItems(TextField t1, TextField t2) {
assign(tmp, t1);
assign(t1, t2);
assign(t2, tmp);
}
private boolean greaterThan(TextField t1, TextField t2) {
boolean greater;
Color t1bg = t1.getBackground();
Color t2bg = t2.getBackground();
t1.setBackground(Color.cyan);
t2.setBackground(Color.cyan);
pause(pauseInterval);
greater = Integer.parseInt(t1.getText()) < Integer.parseInt(t2.getText());
pause(pauseInterval);
t1.setBackground(t1bg);
t2.setBackground(t2bg);
return greater;
}
private void bubbleSort() {
int currentCount = 0;
int n = 0;
showStatus("Sorting ...");
boolean swap = true;
while (swap) {
swap = false;
for (int i = 0; i < items.length - 1; i++) {
if (greaterThan(items[i], items[i + 1])) {
swapItems(items[i], items[i + 1]);
swap = true;
currentCount++;
}
} // for
} // while
showStatus("Sort complete : Swap count = " + currentCount);
} // bubbleSort
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "Clear":
for (int i = 0; i < items.length; i++) {
items[i].setText("");
}
cntLabel = new JLabel("0");
break;
case "Sort":
bubbleSort();
break;
case "Reset":
initItems();
break;
default:
showStatus("Unrecognised button: " + e.toString());
}
}
private void showStatus(String s) {
status.setText(s);
}
}
If I understand correctly, I think that the problem is that you have an unnecessary for loop (the one with the step variable). All you need to do is delete that loop and just have the following instead:
currentCount += 1;
// Alternatively, you could also do 'currentCount = currentCount + 1;' or 'currentCount++;'
So basically, the if statement in your bubbleSort() method should look something like this:
if (greaterThan(items[i], items[i + 1])) {
swapItems(items[i], items[i + 1]);
swap = true;
currentCount += 1;
}

java programing swing application

import java.awt.BorderLayout;
import java.applet.Applet;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.*;
public class MemoryGame implements ActionListener
{
Label mostra;
public int delay = 1000; //1000 milliseconds
public void init()
{
//add(mostra = new Label(" "+0));
}
public void Contador()
{
ActionListener counter = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tempo++;
TempoScore.setText("Tempo: " + tempo);
}
};
new Timer(delay, counter).start();
}
public void updateHitMiss()
{
HitScore.setText("Acertou: " + Hit);
MissScore.setText("Falhou: " + Miss);
PontosScore.setText("Pontos: " + Pontos);
}
private JFrame window = new JFrame("Jogo da Memoria");
private static final int WINDOW_WIDTH = 500; // pixels
private static final int WINDOW_HEIGHT = 500; // pixels
private JButton exitBtn, baralharBtn, solveBtn, restartBtn;
ImageIcon ButtonIcon = createImageIcon("card1.png");
private JButton[] gameBtn = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int Hit, Miss, Pontos;
public int tempo = 0;
private int counter = 0;
private int[] btnID = new int[2];
private int[] btnValue = new int[2];
private JLabel HitScore, MissScore,TempoScore, PontosScore;
private JPanel gamePnl = new JPanel();
private JPanel buttonPnl = new JPanel();
private JPanel scorePnl = new JPanel();
protected static ImageIcon createImageIcon(String path)
{
java.net.URL imgURL = MemoryGame.class.getResource(path);
if (imgURL != null)
{
return new ImageIcon(imgURL);
}
else
{
System.err.println("Couldn't find file: " + path);
return null;
}
}
public MemoryGame()
{
createGUI();
createJPanels();
setArrayListText();
window.setTitle("Jogo da Memoria");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setVisible(true);
Contador();
}
public void createGUI()
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i] = new JButton(ButtonIcon);
gameBtn[i].addActionListener(this);
}
HitScore = new JLabel("Acertou: " + Hit);
MissScore = new JLabel("Falhou: " + Miss);
TempoScore = new JLabel("Tempo: " + tempo);
PontosScore = new JLabel("Pontos: " + Pontos);
exitBtn = new JButton("Sair");
exitBtn.addActionListener(this);
baralharBtn = new JButton("Baralhar");
baralharBtn.addActionListener(this);
solveBtn = new JButton("Resolver");
solveBtn.addActionListener(this);
restartBtn = new JButton("Recomecar");
restartBtn.addActionListener(this);
}
public void createJPanels()
{
gamePnl.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
buttonPnl.add(baralharBtn);
buttonPnl.add(exitBtn);
buttonPnl.add(solveBtn);
buttonPnl.add(restartBtn);
buttonPnl.setLayout(new GridLayout(1, 0));
scorePnl.add(HitScore);
scorePnl.add(MissScore);
scorePnl.add(TempoScore);
scorePnl.add(PontosScore);
scorePnl.setLayout(new GridLayout(1, 0));
window.add(scorePnl, BorderLayout.NORTH);
window.add(gamePnl, BorderLayout.CENTER);
window.add(buttonPnl, BorderLayout.SOUTH);
}
public void setArrayListText()
{
for (int i = 0; i < 2; i++)
{
for (int ii = 1; ii < (gameBtn.length / 2) + 1; ii++)
{
gameList.add(ii);
}
}
}
public boolean sameValues()
{
if (btnValue[0] == btnValue[1])
{
return true;
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if (exitBtn == e.getSource())
{
System.exit(0);
}
if (baralharBtn == e.getSource())
{
//
}
if (solveBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
}
}
for (int i = 0; i < gameBtn.length; i++)
{
if (gameBtn[i] == e.getSource())
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
gameBtn[btnID[0]].setVisible(false);
gameBtn[btnID[1]].setVisible(false);
Hit = Hit +1;
Pontos = Pontos + 25;
}
else
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
Miss = Miss +1;
Pontos = Pontos - 5;
}
counter = 1; //permite 2(3) clikes de cada vez
}
/*if (Pontos <= 0)
{
Pontos=0;
} */
if (counter == 1) // se carregar 1º botão
{
btnID[0] = i;
btnValue[0] = gameList.get(i);
}
if (counter == 2) // se carregar 2º botão
{
btnID[1] = i;
btnValue[1] = gameList.get(i);
}
}
}
if (restartBtn == e.getSource())
{
Hit=0;
Miss=0;
tempo=-1;
Pontos=0;
for (int i = 0; i < gameBtn.length; i++) /* what i want to implement(restart button) goes here, this is incomplete because it only clean numbers and "transforms" into regular JButton, the last two clicks
on the 4x4 grid (btnID[0] and btnID[1]), but i want to clean all the visible
numbers in the grid 4x4, and want to transform all grid 4x4 into default (or
regular color, white and blue) JButton, the grid numbers stay in same order
or position. */
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
}
/*
restartBtn.addActionListener(new ActionListener()
{
JFrame.dispatchEvent(new WindowEvent(JFrame, WindowEvent.WINDOW_CLOSING)); // this line is getting errors (MemoryGame.java:233: error: <identifier> expected
JFrame.dispatchEvent(new WindowEvent(JFrame, WindowEvent.WINDOW_CLOSING));
illegal start of type,')' expected, ';' expected all in the same line )
private JFrame window = new JFrame("Jogo da Memoria");
// something not right, i think frame is replaced by JFrame but i dont know, be
}); */
}
updateHitMiss();
}
public static void main(String[] args)
{
new MemoryGame();
}
}
</code>
Hi,
I want to add a restart button (mouse click), i am running notepadd++, when i click on restart button (recomeçar), it should restart this memory game, all counters set to zero etc, clean the grid 4x4, all numbers that were visible when i click the restart the button they all disaapear (but they are in same place or order) thus only show regular JButtons, the game should go to the starting point like when it first open the application, all numbers are not visible. (the functionality of restart button is equal to exit application and then restart).
Restart button code in lines 215 to 239, issues reported on comments between those lines.
I'm not sure if I fully understand your question, but here's what i think would help:
Add an ActionListener to your button with:
button.addActionListener(new ActionListener() {
});,
with button being the name of your JButton.
Within your ActionListener, call frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));, with frame being the name of your JFrame.
Then, run all of the methods you use to initialize your game (including the one that opens the JFrame).
Comment if you need clarification or more help.

Fail to reset the panel to initial state

I have problem with the Play Again button, which is to reset the panel to initial state.
The Play Again button should reset the panel, it does reshuffle the gameList, but not reset the panel, which means all the buttons remain and lost the ActionListener function.
Here is my program :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import static java.util.Collections.*;
public class MemoryGame extends JFrame
{
private JButton exitButton, replayButton;
private JButton[] gameButton = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int counter = 0;
private int[] buttonID = new int[2];
private int[] buttonValue = new int[2];
public static Point getCenterPosition(int frameWidth, int frameHeight)
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
int x = (dimension.width - frameWidth)/2;
int y = (dimension.height - frameHeight)/2;
return (new Point(x,y));
}
public MemoryGame(String title)
{
super(title);
initial();
}
public void initial()
{
for (int i = 0; i < gameButton.length; i++)
{
gameButton[i] = new JButton();
gameButton[i].setFont(new Font("Serif", Font.BOLD, 28));
gameButton[i].addActionListener(new ButtonListener());
}
exitButton = new JButton("Exit");
replayButton = new JButton("Play Again");
exitButton.addActionListener(new ButtonListener());
replayButton.addActionListener(new ButtonListener());
Panel gamePanel = new Panel();
gamePanel.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameButton.length; i++)
{
gamePanel.add(gameButton[i]);
}
Panel buttonPanel = new Panel();
buttonPanel.add(replayButton);
buttonPanel.add(exitButton);
buttonPanel.setLayout(new GridLayout(1, 0));
add(gamePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
for (int i = 0; i < 2; i++)
{
for (int j = 1; j < (gameButton.length / 2) + 1; j++)
{
gameList.add(j);
}
}
shuffle(gameList);
int newLine = 0;
for (int a = 0; a < gameList.size(); a++)
{
newLine++;
System.out.print(" " + gameList.get(a));
if (newLine == 4)
{
System.out.println();
newLine = 0;
}
}
}
public boolean sameValues()
{
if (buttonValue[0] == buttonValue[1])
{
return true;
}
return false;
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (exitButton == e.getSource())
{
System.exit(0);
}
else if (replayButton == e.getSource())
{
initial();
}
for (int i = 0; i < gameButton.length; i++)
{
if (gameButton[i] == e.getSource())
{
gameButton[i].setText("" + gameList.get(i));
gameButton[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameButton[buttonID[0]].setEnabled(false);
gameButton[buttonID[1]].setEnabled(false);
}
else
{
gameButton[buttonID[0]].setEnabled(true);
gameButton[buttonID[0]].setText("");
gameButton[buttonID[1]].setEnabled(true);
gameButton[buttonID[1]].setText("");
}
counter = 1;
}
if (counter == 1)
{
buttonID[0] = i;
buttonValue[0] = gameList.get(i);
}
if (counter == 2)
{
buttonID[1] = i;
buttonValue[1] = gameList.get(i);
}
}
}
}
}
public static void main(String[] args)
{
int x, y;
int width = 500;
int height = 500;
Point position = getCenterPosition(width, height);
x = position.x;
y = position.y;
JFrame frame = new MemoryGame("Memory Game");
frame.setBounds(x, y, width, height);
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
How can I solve this problem?
EDIT :
Another problem is after reset(), all buttons seem like become sameValue(). I have insert some audio to the buttons, and it's happen in the condition of the ButtonListener. Here is the part :
if (counter == 3)
{
if (sameValues())
{
gameButton[buttonID[0]].setEnabled(false);
gameButton[buttonID[1]].setEnabled(false);
}
Seems like it's satisfy the condition sameValue(), but why?
LATEST UPDATE :
Problem Solved. Latest code is not uploaded.
In the initial() method the code is creating a new GUI. It would be preferable to retain handles to the original controls, and reset them to a 'begin game' state and the correct values (for number).
Alternatives with your current method are to remove() and add() new for every component (not recommended) or to use a CardLayout (not necessary - see first suggestion).
Ok, I've fixed your code.
Be sure to check out my comment to your question and let me know if it works (I did a quick test and it went fine)
package varie;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import static java.util.Collections.shuffle;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MemoryGame extends JFrame {
private JButton exitButton, replayButton;
private JButton[] gameButton = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<>();
private int counter = 0;
private int[] buttonID = new int[2];
private int[] buttonValue = new int[2];
public static Point getCenterPosition(int frameWidth, int frameHeight) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
int x = (dimension.width - frameWidth) / 2;
int y = (dimension.height - frameHeight) / 2;
return (new Point(x, y));
}
public MemoryGame(String title) {
super(title);
initial();
}
public void initial() {
for (int i = 0; i < gameButton.length; i++) {
gameButton[i] = new JButton();
gameButton[i].setFont(new Font("Serif", Font.BOLD, 28));
gameButton[i].addActionListener(new ButtonListener());
}
exitButton = new JButton("Exit");
replayButton = new JButton("Play Again");
exitButton.addActionListener(new ButtonListener());
replayButton.addActionListener(new ButtonListener());
Panel gamePanel = new Panel();
gamePanel.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameButton.length; i++) {
gamePanel.add(gameButton[i]);
}
Panel buttonPanel = new Panel();
buttonPanel.add(replayButton);
buttonPanel.add(exitButton);
buttonPanel.setLayout(new GridLayout(1, 0));
add(gamePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
for (int i = 0; i < 2; i++) {
for (int j = 1; j < (gameButton.length / 2) + 1; j++) {
gameList.add(j);
}
}
shuffle(gameList);
int newLine = 0;
for (int a = 0; a < gameList.size(); a++) {
newLine++;
System.out.print(" " + gameList.get(a));
if (newLine == 4) {
System.out.println();
newLine = 0;
}
}
}
public boolean sameValues() {
if (buttonValue[0] == buttonValue[1]) {
return true;
}
return false;
}
public void reset() {
for(int i = 0; i< gameButton.length; i++){
gameButton[i].setEnabled(true);
gameButton[i].setText("");
for(ActionListener al : gameButton[i].getActionListeners()){
gameButton[i].removeActionListener(al);
}
gameButton[i].addActionListener(new ButtonListener());
}
buttonID = new int[2];
buttonValue = new int[2];
counter = 0;
shuffle(gameList);
int newLine = 0;
for (int a = 0; a < gameList.size(); a++) {
newLine++;
System.out.print(" " + gameList.get(a));
if (newLine == 4) {
System.out.println();
newLine = 0;
}
}
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (exitButton.equals(e.getSource())) {
System.exit(0);
} else if (replayButton.equals(e.getSource())) {
reset();
} else {
for (int i = 0; i < gameButton.length; i++) {
if (gameButton[i].equals(e.getSource())) {
gameButton[i].setText("" + gameList.get(i));
gameButton[i].setEnabled(false);
counter++;
if (counter == 3) {
if (sameValues()) {
gameButton[buttonID[0]].setEnabled(false);
gameButton[buttonID[1]].setEnabled(false);
} else {
gameButton[buttonID[0]].setEnabled(true);
gameButton[buttonID[0]].setText("");
gameButton[buttonID[1]].setEnabled(true);
gameButton[buttonID[1]].setText("");
}
counter = 1;
}
if (counter == 1) {
buttonID[0] = i;
buttonValue[0] = gameList.get(i);
}
if (counter == 2) {
buttonID[1] = i;
buttonValue[1] = gameList.get(i);
}
}
}
}
}
}
public static void main(String[] args) {
int x, y;
int width = 500;
int height = 500;
Point position = getCenterPosition(width, height);
x = position.x;
y = position.y;
JFrame frame = new MemoryGame("Memory Game");
frame.setBounds(x, y, width, height);
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Categories