here i attach the picture of my apps so I want to create an app that can be use and install for me and my friends on laptop. What this app will do :
1. this app will have 20 numbers and the initial numbers will be "0" before they click the start button.
The first 10 numbers in the textbox, users can insert any numbers thats the range only between 0-9 only but for the last 10 numbers, users cannot insert any numbers.
this app have 2 buttons which are save and start button.
when the users click start button even the users didnt insert anything in the first 10 textbox, the 1st number will start counting from 0-9, after the 1st number finish count until 9, the second number will continue counting from 0-9 and 3rd-20th number will also do the same until all the 20 numbers in the textbox become 9999999999999999999, then it will stop counting.
when the users insert numbers in first three textbox and press start button, the number will start counting from the 4th textbox, until 20th numbers and until the 4-20th numbers become ***999999999999999999.
but every time the numbers changing, for example, when 1st number start counting like 100000000000000000000, users will click save button and it will save the numbers in the textarea which is located in the middle of this app and at the same time it will automatically create a folder in the users computer and the numbers will also save in that folder.
when the users transfer that folder from their laptop to their phone, all the numbers will save automatically as contact numbers in their phone.
here in my code, I dont know how to make the start button to run the numbers automatically once the start button click, in my code, the number will only change everytime when the start button click, i just want to click the start button only one time and the number will count automatically,anyone know how to do it? and the save button also i have no idea how to do it.`[ import javax.swing.;
import java.awt.;
import java.awt.event.*;
public class b extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
JTextField t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, t20;
JButton start, save;
JTextArea ta;
public b() {
Container pane = getContentPane();
pane.setLayout(new GridLayout(3, 1));
panel.setLayout(new FlowLayout());
panel.add(t1 = new JTextField(("0"), 2));
panel.add(t2 = new JTextField(("0"), 2));
panel.add(t3 = new JTextField(("0"), 2));
panel.add(t4 = new JTextField(("0"), 2));
panel.add(t5 = new JTextField(("0"), 2));
panel.add(t6 = new JTextField(("0"), 2));
panel.add(t7 = new JTextField(("0"), 2));
panel.add(t8 = new JTextField(("0"), 2));
panel.add(t9 = new JTextField(("0"), 2));
panel.add(t10 = new JTextField(("0"), 2));
panel.add(t11 = new JTextField(("0"), 2));
panel.add(t12 = new JTextField(("0"), 2));
panel.add(t13 = new JTextField(("0"), 2));
panel.add(t14 = new JTextField(("0"), 2));
panel.add(t15 = new JTextField(("0"), 2));
panel.add(t16 = new JTextField(("0"), 2));
panel.add(t17 = new JTextField(("0"), 2));
panel.add(t18 = new JTextField(("0"), 2));
panel.add(t19 = new JTextField(("0"), 2));
panel.add(t20 = new JTextField(("0"), 2));
t11.setEditable(false);
t12.setEditable(false);
t12.setEditable(false);
t13.setEditable(false);
t14.setEditable(false);
t15.setEditable(false);
t16.setEditable(false);
t17.setEditable(false);
t18.setEditable(false);
t19.setEditable(false);
t20.setEditable(false);
ta = new JTextArea();
ta.setEditable(false);
panel1.setLayout(new FlowLayout());
panel1.add(save = new JButton("Save"));
panel1.add(start = new JButton("Start"));
pane.add(panel);
pane.add(ta);
pane.add(panel1);
t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
t4.addActionListener(this);
t5.addActionListener(this);
t6.addActionListener(this);
t7.addActionListener(this);
t8.addActionListener(this);
t9.addActionListener(this);
t10.addActionListener(this);
t11.addActionListener(this);
t12.addActionListener(this);
t13.addActionListener(this);
t14.addActionListener(this);
t15.addActionListener(this);
t16.addActionListener(this);
t17.addActionListener(this);
t18.addActionListener(this);
t19.addActionListener(this);
t20.addActionListener(this);
save.addActionListener(this);
start.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
int count = Integer.parseInt(t1.getText());
if (obj == start) {
if (count < 9) {
count++;
t1.setText("" + count);
}
else {
count = 0;
t1.setText("" + count);
count = Integer.parseInt(t2.getText());
if (count < 9) {
count++;
t2.setText("" + count);
}
else {
count = 0;
t2.setText("" + count);
count = Integer.parseInt(t3.getText());
if (count < 9) {
count++;
t3.setText("" + count);
}
else {
count = 0;
t3.setText("" + count);
count = Integer.parseInt(t4.getText());
if (count < 9) {
count++;
t4.setText("" + count);
}
else {
count = 0;
t4.setText("" + count);
count = Integer.parseInt(t5.getText());
if (count < 9) {
count++;
t5.setText("" + count);
}
else {
count = 0;
t5.setText("" + count);
count = Integer.parseInt(t6.getText());
if (count < 9) {
count++;
t6.setText("" + count);
}
else {
count = 0;
t6.setText("" + count);
count = Integer.parseInt(t7.getText());
if (count < 9) {
count++;
t7.setText("" + count);
}
else {
count = 0;
t7.setText("" + count);
count = Integer.parseInt(t8.getText());
if (count < 9) {
count++;
t8.setText("" + count);
}
else {
count = 0;
t8.setText("" + count);
count = Integer.parseInt(t9.getText());
if (count < 9) {
count++;
t9.setText("" + count);
}
else {
count = 0;
t9.setText("" + count);
count = Integer.parseInt(t10.getText());
if (count < 9) {
count++;
t10.setText("" + count);
}
else {
count = 0;
t10.setText("" + count);
count = Integer.parseInt(t11.getText());
if (count < 9) {
count++;
t11.setText("" + count);
}
else {
count = 0;
t11.setText("" + count);
count = Integer.parseInt(t12.getText());
if (count < 9) {
count++;
t12.setText("" + count);
}
else {
count = 0;
t12.setText("" + count);
count = Integer.parseInt(t13.getText());
if (count < 9) {
count++;
t13.setText("" + count);
}
else {
count = 0;
t13.setText("" + count);
count = Integer.parseInt(t14.getText());
if (count < 9) {
count++;
t14.setText("" + count);
}
else {
count = 0;
t14.setText("" + count);
count = Integer.parseInt(t15.getText());
if (count < 9) {
count++;
t15.setText("" + count);
}
else {
count = 0;
t15.setText("" + count);
count = Integer.parseInt(t16.getText());
if (count < 9) {
count++;
t16.setText("" + count);
}
else {
count = 0;
t16.setText("" + count);
count = Integer.parseInt(t17.getText());
if (count < 9) {
count++;
t17.setText("" + count);
}
else {
count = 0;
t17.setText("" + count);
count = Integer.parseInt(t18.getText());
if (count < 9) {
count++;
t18.setText("" + count);
}
else {
count = 0;
t18.setText("" + count);
count = Integer.parseInt(t19.getText());
if (count < 9) {
count++;
t19.setText("" + count);
}
else {
count = 0;
t19.setText("" + count);
count = Integer.parseInt(t20.getText());
if (count < 9) {
count++;
t20.setText("" + count);
}
else {
count = 0;
t20.setText("0");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
public static void main (String[] args) {
b frame1 = new b();
frame1.setTitle("bb");
frame1.setSize(650, 400);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
}
]2`
Related
I am working on a simple TicTacToe game with java swing and everything works properly, but whenever the GUI updates the layout changes. This happens with the buttons getting bigger when they are pressed and change to display an 'x' or an 'o' or when the entire game stops and displays a new label saying who won. I'm pretty much a beginner when it comes to programs like this, and the code itself is a huge hodgepodge of copy-pastes from programs that I have made with each separate components, so I figure that could be a reason for this issue.
Code below:
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JTextField;
import javax.swing.Timer;
import java.text.DecimalFormat;
public class test extends JFrame {
private JButton [] buttons = new JButton[9];
private char player = 'x';
private JLabel turnLabel = new JLabel("Player turn: ");
private JLabel turn = new JLabel(Character.toString(player).toUpperCase());
private JLabel winnerLabel = new JLabel("");
private JLabel timeLabel = new JLabel("");
private byte centiseconds = 0;
private byte seconds = 0;
private short minutes = 0;
private DecimalFormat timeFormatter;
private Timer timer;
/* Constructor initializes the Frame,
creates GUI components, and adds them
using a GridBagLayout. */
test() {
GridBagConstraints layoutConst; // Used to specify GUI component layout
// Set frame's title
setTitle("TicTacToe");
// Use a GridBagLayout
setLayout(new GridBagLayout());
// Create GridBagConstraints
layoutConst = new GridBagConstraints();
createObjects(layoutConst);
timer.start();
}
public void createObjects(GridBagConstraints layoutConst) {
int i = 0;
for(int r = 0; r <= 2; r++) {
for(int c = 0; c <= 2; c++) {
buttons[i] = new JButton();
buttons[i].setText(" ");
layoutConst.gridx = r;
layoutConst.gridy = c;
layoutConst.ipadx = 70;
layoutConst.ipady = 70;
add(buttons[i], layoutConst);
buttons[i].addActionListener(e -> {
layoutConst.insets = new Insets(0, 0, 0, 0);
JButton clickedBtn = (JButton) e.getSource();
clickedBtn.setText(String.valueOf(player));
clickedBtn.setEnabled(false);
if (player == 'x')
player = 'o';
else
player = 'x';
turn.setText(Character.toString(player).toUpperCase());
findWinner();
});
i++;
}
createLabels(layoutConst);
}
}
public void createLabels(GridBagConstraints layoutConst) {
layoutConst.gridx = 5;
layoutConst.gridy = 1;
layoutConst.ipady = 0;
layoutConst.ipadx = 0;
layoutConst.insets = new Insets(10, 10, 10, 10);
add(turnLabel, layoutConst);
layoutConst.gridx = 6;
layoutConst.gridy = 1;
layoutConst.gridwidth = 1;
layoutConst.insets = new Insets(0, 0, 0, 0);
add(turn, layoutConst);
layoutConst.gridx = 6;
layoutConst.gridy = 2;
layoutConst.gridwidth = 1;
layoutConst.insets = new Insets(0, 0, 0, 0);
add(winnerLabel, layoutConst);
layoutConst.gridx = 7;
layoutConst.gridy = 0;
layoutConst.insets = new Insets(0, 0, 0, 0);
add(timeLabel, layoutConst);
timeFormatter = new DecimalFormat("00");
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (centiseconds >= 0 && centiseconds != 100) {
centiseconds++;
}
else if(centiseconds == 100) {
seconds++;
centiseconds = 0;
}
else if(seconds == 60 && centiseconds == 100) {
minutes++;
seconds = 0;
centiseconds = 0;
}
timeLabel.setText(timeFormatter.format(minutes) + ":"
+ timeFormatter.format(seconds) + "."
+ timeFormatter.format(centiseconds));
}
});
timeLabel.setText(timeFormatter.format(minutes) + ":"
+ timeFormatter.format(seconds) + "."
+ timeFormatter.format(centiseconds));
}
public void findWinner() {
if (checkForWinner()) {
if (player == 'x') {
player = 'o';
}
else {
player = 'x';
}
winnerLabel.setText("Player " + Character.toString(player) + " wins!");
timer.stop();
}
else if (checkIfMatchDraw()) {
winnerLabel.setText("It's a draw!");
timer.stop();
}
}
public boolean checkIfMatchDraw() {
boolean gridsFull = true;
for (int i = 0; i < 9; i++) {
if (buttons[i].getText().equals(" ")) {
gridsFull = false;
}
}
return gridsFull;
}
public boolean checkForWinner() {
return checkAllRows() || checkAllColumns() || checkTheDiagonals();
}
public boolean checkAllRows() {
int i = 0;
for (int j = 0; j < 3; j++) {
if (buttons[i].getText().equals(buttons[i + 1].getText()) && buttons[i].getText().equals(buttons[i + 2].getText())
&& !buttons[i].getText().equals(" ")) {
return true;
}
i = i + 3;
}
return false;
}
public boolean checkAllColumns() {
int i = 0;
for (int j = 0; j < 3; j++) {
if (buttons[i].getText().equals(buttons[i + 3].getText()) && buttons[i].getText().equals(buttons[i + 6].getText())
&& !buttons[i].getText().equals(" ")) {
return true;
}
i++;
}
return false;
}
public boolean checkTheDiagonals() {
if (buttons[0].getText().equals(buttons[4].getText()) && buttons[0].getText().equals(buttons[8].getText())
&& !buttons[0].getText().equals(" "))
return true;
else
return buttons[2].getText().equals(buttons[4].getText()) && buttons[2].getText().equals(buttons[6].getText())
&& !buttons[2].getText().equals(" ");
}
/* Creates a Frameand makes it visible */
public static void main(String[] args) {
// Creates Frame and its components
test myFrame = new test();
// Terminate program when window closes
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Resize window to fit components
myFrame.pack();
// Display window
myFrame.setVisible(true);
}
}
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Creating random numbers with no duplicates
(20 answers)
Closed 10 months ago.
In this code, when a button is pressed, it shows a random number. I don't want that number to repeat itself. I have it so that when a big button is pushed, a number generates 1-10. I want it so that IF that number is duplicated it runs the code again to find another number that works. I've been working on it for a while and tried a lot of things. Any tips/tricks would be great. Thank you.
class HiLow extends JFrame implements ActionListener{
int NumberGenerated;
JButton Push, High,Low, Bank;
JLabel Score;
int helpInt = 0;
int counterInt = 0;
ArrayList<Integer> numberList = new ArrayList<Integer>();
int size = numberList.size();
boolean hp = true;
HiLow(){
JFrame l = new JFrame();
// JOptionPane.showMessageDialog(l, "Press the 'Push' button\nThen look at the number rolled\nThere will be numbers from 1-10\nThen click higher or lower\nYou can bank your points using the bank button\nMost points after 5 spins wins\nGood luck!");
Push = new JButton("Push For Number");
High = new JButton("Higher");
Low = new JButton("Lower");
Bank = new JButton("Bank Points");
Score = new JLabel("");
add(Push);
add(High);
add(Low);
add(Bank);
add(Score);
Push.addActionListener(this);
High.addActionListener(this);
Low.addActionListener(this);
Bank.addActionListener(this);
Push.setBounds(150,150,200,200);
High.setBounds(10,420,100,50);
Low.setBounds(390,420,100,50);
Bank.setBounds(10,10,100,50);
Score.setBounds(205,100, 150,50);
High.setEnabled(false);
Low.setEnabled(false);
setLayout(null);
setSize(500, 500);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Push){
helpInt++;
int max = 10;
int min = 1;
int range = max - min + 1;
// if(size >= 5) {
// High.setEnabled(false);
// Low.setEnabled(false);
// Push.setEnabled(false);
// }
do {
int NumberGenerated = (int)(Math.random() * range) + min;
if(numberList.contains(NumberGenerated)) {
High.setEnabled(false);
Low.setEnabled(false);
Push.setEnabled(true);
invalidate();
validate();
repaint();
}else {
String score = String.valueOf(NumberGenerated);
Score.setText("You Rolled: " + score);
numberList.add(NumberGenerated);
System.out.println(numberList);
hp=false;
}
}while(hp == true);
invalidate();
validate();
repaint();
if(helpInt == 1) {
High.setEnabled(true);
Low.setEnabled(true);
Push.setEnabled(false);
}
}
////////////////
if(e.getSource()==High){
helpInt--;
counterInt++;
if(helpInt == 0) {
High.setEnabled(false);
Low.setEnabled(false);
Push.setEnabled(true);
}
//if(size >= 5) {
// High.setEnabled(false);
// Low.setEnabled(false);
// Push.setEnabled(false);
//}
}
////////////////
if(e.getSource()==Low){
helpInt--;
counterInt++;
if(helpInt == 0) {
High.setEnabled(false);
Low.setEnabled(false);
Push.setEnabled(true);
}
//if(size >= 5) {
// High.setEnabled(false);
// Low.setEnabled(false);
// Push.setEnabled(false);
//}
}
////////////////
}
}
I have got an array of 30 buttons []. I have a variable buttonClicked. When I press the button how can I get the index and store the index number in the buttonClicked?
Thanks :)
JButton [] buttons = new JButton[30];
for(int i = 1; i <= 30; i++)
{
int btnNumber = (i > 10 && i <= 20) ? (31 - i) : i;
System.out.printf("i = %d, btnNumber = %d%n", i, btnNumber);
buttons[btnNumber - 1] = new JButton("label " + btnNumber);
//buttons[btnNumber - 1].setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttons[btnNumber - 1].setBorder(BorderFactory.createEtchedBorder());
buttons[btnNumber - 1].setOpaque(true);
buttons[btnNumber - 1].setBackground(Color.white);
//Puts the player 1 piece on button 1,3,5,7,9 and player 2 piece on button 2,4,6,8,10
if ((btnNumber - 1) < 10)
{
if (((btnNumber - 1) % 2) == 0)
{
buttons[btnNumber - 1].setIcon(piece1);
}
else
{
buttons[btnNumber - 1].setIcon(piece2);
}
}
centerPanel.add(buttons[btnNumber - 1]);
}
//Below is what I am attempting to do, I know is not correct.
public void move()
{
Move = dice.getDiceResult();
int buttonClicked = 0;
if(playerOneTurn =true)
{
buttonclicked + diceResult();
}
//revised
public class MyActionListener implements ActionListener {
Dice dice;
private boolean playerOneTurn = true;
private boolean playerTwoTurn = false;
#Override
public void actionPerformed(ActionEvent e)
{
String num = e.getActionCommand();
int index = Integer.parseInt(num);
int move = dice.getDiceResult();
int positionLanding = 0;
if(playerOneTurn = true)
{
positionLanding = index + move;
positionLanding.setIcon("piece1");//how can I set the image Icon to this position?
}
}
}
1) putClientProperty
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
and getClientProperty
public class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
2) ActionCommand
You can find the button in ActionEvent.getSource(). To find the index it is just a matter of iterating through the array, looking for that particular button.
The prettiest way is using Component.setName. Then you don't even need to maintain variables with your components - you can go straight off of the name
I prefer the strategy suggested by aioobe, but here is another way.
buttons[btnNumber - 1] = new JButton("label " + btnNumber);
buttons[btnNumber - 1].setActionCommand("" + btnNumber);
// ...
// ...later.. in the actionPerformed() method
String num = actionEvent.getActionCommand();
int index = Integer.parseInt(num);
// ..proceed..
Trying to get the final part of this game to work. Its a hangman game, I just need it to display correct guesses where they are in the word.
This is the snippet of code of when a correct guess is given
else
{
int alreadyGuessed = guesses.indexOf(guess);
if (alreadyGuessed == -1)
{
guesses = guesses + guess + "";
jlbWord.setText("Word: " + charWord[currentGuess]);
}
else{}
}
Right now it simply shows each letter. I can also set it, so it shows each one as they are typed in but its not in the right order, which makes it much more difficult for the user to guess what the word is.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.Dimension;
public class RightPanel extends JPanel implements KeyListener
{
JLabel jlbMissed, jlbWord, jlbTimer;
Color btnColor;
JComboBox jcbDifficulty;
JButton jbtStart, jbtQuit;
String[] difficulties = {"Easy", "Medium", "Hard"};
String[] words = {"First", "Next", "Hello", "World"};
char guess;
String word, guesses = "";
char[] charWord;
public static int incorrectGuesses = 0;
boolean clockIsRunning = false;
boolean gameInPlay = false;
int sec = 0;
int min = 0;
public RightPanel()
{
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
Random ran = new Random(); //
int rand = ran.nextInt(4); // Generates random number then selects word from words array
word = words[rand]; //
charWord = word.toCharArray();
ActionHandler actionHandler = new ActionHandler();
jlbMissed = new JLabel("Missed: ");
jlbWord = new JLabel("Word: ");
jlbTimer = new JLabel("Time: " + "0:00");
jbtStart = new JButton("Start");
jbtQuit = new JButton("Quit");
jcbDifficulty = new JComboBox();
jbtStart.addActionListener(actionHandler);
jbtQuit.addActionListener(actionHandler);
jcbDifficulty.addKeyListener(this);
jbtStart.addKeyListener(this);
for (int i = 0; i < 3; i++)
{
jcbDifficulty.addItem(difficulties[i]); // Creates Difficutly ComboBox
}
this.add(jcbDifficulty, getConstraints(0,0,1,1, GridBagConstraints.WEST));
this.add(jlbMissed, getConstraints(0,1,1,1, GridBagConstraints.WEST));
this.add(jlbWord, getConstraints(0,2,1,1, GridBagConstraints.WEST));
this.add(jlbTimer, getConstraints(0,4,1,1, GridBagConstraints.WEST));
this.add(jbtStart, getConstraints(0,6,1,1, GridBagConstraints.WEST));
this.add(jbtQuit, getConstraints(0,7,1,1, GridBagConstraints.WEST));
}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e)
{
guess = e.getKeyChar();
if (gameInPlay == false)
{
JOptionPane.showMessageDialog(this, "You have not started the game yet!", "Game has not Started", JOptionPane.ERROR_MESSAGE);
System.out.println("Game Not in Play");
}
else
{
if (Character.isLetter(guess))
{
if (incorrectGuesses > 11)
{
clockIsRunning = false;
gameInPlay = false;
JOptionPane.showMessageDialog(this, "You Killed Him! \nThe word was " + word, "He Ceases to Exist", JOptionPane.ERROR_MESSAGE);
jbtStart.setText("Retry?");
jbtStart.setBackground(Color.RED);
}
else
{
int currentGuess = word.indexOf(guess);
if (currentGuess == -1)
{
int alreadyGuessed = guesses.indexOf(guess);
if (alreadyGuessed == -1)
{
guesses = guesses + guess + "";
System.out.println(alreadyGuessed);
System.out.println(guesses);
String temp = jlbMissed.getText();
jlbMissed.setText(temp + guess + ", ");
incorrectGuesses++;
leftPanel.hangmanPic.setIcon(leftPanel.image[RightPanel.incorrectGuesses]);
}
else {}
}
else
{
int alreadyGuessed = guesses.indexOf(guess);
if (alreadyGuessed == -1)
{
guesses = guesses + guess + "";
jlbWord.setText("Word: " + charWord[currentGuess]);
}
else{}
}
}
}
else
JOptionPane.showMessageDialog(this, "That is not a valid guess!\n Please enter a character from A-Z", "Invalid Guess", JOptionPane.ERROR_MESSAGE);
}
}
private GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth, int gridheight, int anchor)
{
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5,5,5,5);
c.ipadx = 0;
c.ipady = 0;
c.gridx = gridx;
c.gridy = gridy;
c.gridwidth = gridwidth;
c.gridheight = gridheight;
c.anchor = anchor;
return c;
}
class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == jbtStart)
{
if (clockIsRunning == true){}
else
{
if (jbtStart.getText() == "Start")
{
btnColor = jbtStart.getBackground();
clockIsRunning = true;
MyTimer timer = new MyTimer();
timer.start();
gameInPlay = true;
}
else if (jbtStart.getText() == "Retry?")
{
jbtStart.setText("Start");
jbtStart.setBackground(btnColor);
jlbTimer.setText("Time: " + "0:00");
sec = 0;
min = 0;
MyTimer timer = new MyTimer();
timer.start();
clockIsRunning = true;
gameInPlay = true;
incorrectGuesses = 0;
guesses = "";
jlbMissed.setText("Missed: ");
jlbWord.setText("Word: ");
leftPanel.hangmanPic.setIcon(leftPanel.image[RightPanel.incorrectGuesses]);
Random ran = new Random();
int rand = ran.nextInt(4);
word = words[rand];
}
}
}
else if (source == jbtQuit)
{
System.exit(0);
}
}
}
class MyTimer extends Thread
{
public void run()
{
while(true)
{
if(!clockIsRunning)
break;
try
{
Thread.sleep(1000);
}
catch (InterruptedException ecp)
{
}
if (sec == 59)
{
min++;
sec = 0;
}
else
sec++;
if(sec < 10)
jlbTimer.setText("Time:" + min+":0"+sec);
else
jlbTimer.setText("Time:" + min+":"+sec);
}
}
}
}
Yikes.
You should refactor your code and keep the guesses in a TreeSet<Character> data structure. It assures, that each character is stored only once and that an iterator returns all stored chars in ascending order.
Snippet:
Set<Character> guesses = new HashSet<Character>();
// add a guess
guesses.add('e');
guesses.add('r');
guesses.add('a');
guesses.add('e'); // will not be added, already in the set
// test
if (guesses.contains('e')) { ... }
// test if a word is "guessed"
boolean foundIt = true;
for (char c:word.toCharArray()) {
if (!guesses.contains(c)) {
foundIt = false;
break;
}
}
// foundIt is true if all chars of word have been guessed
// print
for (char c:guesses)
System.out.print(c); // prints: aer
i'm posting a simple game code, written in java. It took my hours today to write this but now i'm stuck! The problem is, in the second level of this game (after failure or success) i can't see the red tiles. It works only the first time.
games logic:
it starts up with a 3x3 matrix and rebound the dimension of this matrix in case of success (testing the ability of memory, memorising the coordinates of red tiles in 1200 ms). So we show the red tiles first, than we check the estimations. If there became a wrong try, failure!. If it is a bigger matrix than 3x3, it gets smaller.
the code is a little bit long but just one class, so it is so easy yo execute it. If you have time i would be appreciate.
So there it goes:
package skeleton;
public class Memory extends JFrame implements ActionListener {
private static final long serialVersionUID = 5963518754230629235L;
private static int minDimX = 3, minDimY = 3;
private static int maxDimX = 15, maxDimY = 15;
private static int counter = 13;
private static int memoriseTime = 1200; // milliseconds
private static int memGridWidthX = 60;
private static int memGridWidthY = 60;
private JPanel centerPanel;
private JButton memTile;
private Random generator;
private int memGridDimX, memGridDimY, coef, numberOfMemTilesToGuess;
int[][] memTileCoordinates;
int[] randomNums;
Border grayBorder = LineBorder.createGrayLineBorder();
public Memory(int xDim, int yDim) {
waitALittleBit(1300);
memGridDimX = xDim;
memGridDimY = yDim;
coef = 3;
numberOfMemTilesToGuess = memGridDimX*memGridDimY / coef;
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(memGridDimY, memGridDimX, 0, 0));
add(centerPanel, BorderLayout.CENTER);
System.out.println("int[" + memGridDimX + "][" + memGridDimY + "] array is created ");
randomNums = new int[numberOfMemTilesToGuess];
for (int i = 0 ; i < numberOfMemTilesToGuess ; i ++) {
System.out.println("> we are in for the "+ (i+1) +". time!");
int randomNum;
boolean randomNumberAlreadySelected = false;
do {
randomNum = calculateARandomNumber(memGridDimX * memGridDimY);
if (i != 0) { //for the first time, we don't need to compare any numbers
randomNumberAlreadySelected = isThisRandomNumberExistInAlreadyFoundRandomNumbersArray(randomNum, randomNums, i);
if (randomNumberAlreadySelected)
System.out.println("######## RECALCULATING RANDOM NUMBER !! ##########");
else
System.out.println("They are not equal, go on!");
}
} while (randomNumberAlreadySelected);
randomNums[i] = (Integer)randomNum;
}
//show the memory tiles
setMemTiles(randomNums, true);
waitALittleBit(memoriseTime);
//hide the memory tiles
setMemTiles(randomNums, false);
}
private int calculateARandomNumber(int limit) {
generator = new Random();
System.out.println("* Calculating random number which is smaller than " + memGridDimX * memGridDimY);
int randomNum = generator.nextInt() % (memGridDimX * memGridDimY);
System.out.println("- Calculated random number: " + randomNum);
if (randomNum < 0) {
System.out.println(".. it is negative, so we add: " + memGridDimX * memGridDimY);
randomNum += memGridDimX * memGridDimY;
}
System.out.println(".. and we add 1 to have a grid array between 1 and 12");
randomNum += 1;
System.out.println(".. and our new random number is: " + randomNum);
return randomNum;
}
private boolean isThisRandomNumberExistInAlreadyFoundRandomNumbersArray(int number, int[] numberArr, int numberArrSize) {
for (int j = 0 ; j < numberArrSize ; j ++) {
System.out.println("# Comparing random number: " + number + " and " + (j+1) + ". random number selected earlier: " + numberArr[j]);
if (number == numberArr[j])
return true;
}
return false;
}
private void setMemTiles(int[] randomNums, boolean showMemTiles) {
centerPanel.removeAll();
memTileCoordinates = new int[randomNums.length][2];
for (int i = 1 ; i <= memGridDimY ; i ++) {
for (int j = 1 ; j <= memGridDimX ; j ++) {
int rnX = -1;
int rnY = -1;
boolean isMemTile = false;
for (int k = 0 ; k < randomNums.length ; k ++) {
int rn = randomNums[k];
if (rn % memGridDimX == 0) {
rnY = rn / memGridDimX;
rnX = memGridDimX;
} else {
rnY = rn / memGridDimX + 1;
rnX = rn % memGridDimX;
}
if (i == 1 && j == 1 && !showMemTiles) { //do it once
System.out.println("********* ************");
System.out.println("Random label number: " + rn + " and it's position in the grid: " + rnX + "," + rnY);
memTileCoordinates[k][0] = rnX;
memTileCoordinates[k][1] = rnY;
System.out.println("> Memory Tiles coordinates: " + memTileCoordinates[k][0] + "," + memTileCoordinates[k][1]);
System.out.println("> Memory Tiles length: " + memTileCoordinates.length);
System.out.println("********* ************");
}
if (rnX == j && rnY == i)
isMemTile = true;
}
memTile = new JButton();
if (isMemTile) {
update(getGraphics());
if (showMemTiles) {
memTile.setBackground(Color.red);
System.out.println("%%%% PAINTING MEM TILES IN RED %%%%");
} else
memTile.setBackground(Color.white);
update(getGraphics());
} else
memTile.setBackground(Color.white);
if (!showMemTiles) // we listen actions after the memory tiles disappears
memTile.addActionListener(this);
centerPanel.add(memTile);
update(getGraphics());
}
}
setJPanelSettings();
}
private void setJPanelSettings() {
setSize(memGridDimX * memGridWidthX, memGridDimY * memGridWidthY);
setTitle("Memory :: " + memGridDimX + "x" + memGridDimY);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
private void waitALittleBit(long waitingMillisSeconds) {
long t0 = System.currentTimeMillis();
long t1 ;
do {
t1 = System.currentTimeMillis();
} while (t1 - t0 < waitingMillisSeconds);
}
public static void main(String[] args) {
new Memory(minDimX,minDimY);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(">>> An action came >>>");
JButton memTile = (JButton) e.getSource();
Dimension size = memTile.getSize();
int chosenMemTileDimX = memTile.getX();
int chosenMemTileDimY = memTile.getY();
int chosenMemTilePosX = chosenMemTileDimX / size.width + 1; // we add 1 becausee we present our tile numbers as 1:1, 1:2, ... ( instead of 0:0,0:1, ... )
int chosenMemTilePosY = chosenMemTileDimY / size.height + 1;
System.out.println("Chosen Tile's x dimension: " + chosenMemTileDimX + " ans y dimension: " + chosenMemTileDimY);
System.out.println("Chosen Tile's width: " + size.width + " and height: " + size.height);
System.out.println("Chosen Tile's coordinates: " + chosenMemTilePosX + ", " + chosenMemTilePosY);
boolean tileIsMemTile = false;
System.out.println("Memory Tiles Coordinates: ");
for (int i = 0 ; i < memTileCoordinates.length ; i ++) {
int memTileDimX = memTileCoordinates[i][0];
int memTileDimY = memTileCoordinates[i][1];
System.out.println("x: " + memTileDimX + ", y: " + memTileDimY);
if (chosenMemTilePosX == memTileDimX && chosenMemTilePosY == memTileDimY)
tileIsMemTile = true;
}
if (tileIsMemTile) {
System.out.println("!!! Right Tile !!!");
memTile.setBackground(Color.red);
numberOfMemTilesToGuess -= 1;
System.out.println("It rest " + numberOfMemTilesToGuess + " tiles to guess");
} else {
System.out.println("!!! Wrong Tile !!!");
Icon falseTileIcon;
try {
falseTileIcon = new ImageIcon(getClass().getResource("wrong.png"));
if (falseTileIcon.getIconHeight() > 0)
memTile.setIcon(falseTileIcon);
} catch (Exception e1) {
memTile.setBackground(Color.black);
}
update(getGraphics()); // good trick!!
waitALittleBit(1000);
//TODO !!! FAILED IN LEVEL MESSAGE !!!
dispose();
if (memGridDimX == minDimX && ( memGridDimY == minDimY || memGridDimY == minDimY + 1))
new Memory(minDimX, minDimY);
else if (memGridDimX == memGridDimY)
new Memory(memGridDimX - 1, memGridDimY);
else
new Memory(memGridDimX, memGridDimY -1);
}
System.out.println(">>> Action processed >>>");
if (numberOfMemTilesToGuess == 0) {
System.out.println("\n END OF THE LEVEL");
System.out.println("Congratulations, you guessed all the tiles without error !! \n");
dispose();
//TODO !!!! SHOW INTERLEVEL INFORMATION !!!!
if (memGridDimX != maxDimX && memGridDimY != maxDimY) {
if (memGridDimX == memGridDimY)
new Memory(memGridDimX, memGridDimY + 1);
else
new Memory(memGridDimX + 1, memGridDimY);
} else
System.out.println("You have a really good memory my friend!");
}
}}
I used update(getGraphics()); many times, it was just for a test...
Thanks in advance.
You where told in your last posting to NOT use the update() method.
do
{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < waitingMillisSeconds);
Also, never use a tight loop like that. Its just as bad as using Thread.sleep(...);
You where given suggestions in your last posting!
I think you can use LWJGL, which is a java game library.
https://www.lwjgl.org
Some of the issues may be due to the thread on which the various bit of code run. The first time through you are running on the "Main" thread, and to be completely correct calls to update the AWT/Swing GUI should be done using the "Event Dispatcher Thread".
The actionPerformed method is called from the "Event Dispatcher Thread" and so then the second time you call into the constructor for Memory you are in this thread.
Also, aside from the fact you have implemented a delay with a spin-loop, which is not efficient; you should not delay the "Event Dispatcher Thread".
See this short overview: http://www.javamex.com/tutorials/threads/swing_ui.shtml