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;
}
Related
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();
}
Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}
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.
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);
}
}
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();
}
}