I don't understand the int a; in the main that I called st in the Action listener. I want the st to decrease for 1 everytime a cetain button is clicked but it seems to work separetly for each button. I made it so it writes it out on a button each time I press another button to test it and it only works for the first button and then it just stays the same. (I hope I'm making any sense)
Here is my code, Main class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Start {
public static int a;
public static JButton[][] gumbi = new JButton[15][15];
public static void main(String[] args) {
JFrame okno = new JFrame("Nonogram");
okno.setVisible(true);
okno.setSize(700, 700);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
okno.add(panel);
JPanel polje = new JPanel(new GridLayout(15, 15));
panel.add(polje, BorderLayout.CENTER);
a = 0;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (i < 5 && j < 5) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.GREEN);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
} else if (i < 5 || j < 5) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.YELLOW);
// gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
gumbi[i][j].setEnabled(false);
} else {
if (Math.random() <= 0.6) {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("3");
polje.add(gumbi[i][j]);
} else {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("4");
polje.add(gumbi[i][j]);
}
}
if (gumbi[i][j].getText() == "3") {
a += 1;
}
if (i == 14 && j == 14) {
gumbi[i][j].setText("" + a);
}
}
}
}
}
and ActionListener:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Listener implements ActionListener {
JButton[][] gumbi = Start.gumbi;
int st = Start.a;
public Listener(JButton[][] gumbi) {
this.gumbi = gumbi;
}
public void actionPerformed(ActionEvent e){
JButton gumb = (JButton) e.getSource();
if( gumb.getBackground() == Color.WHITE){
gumb.setBackground(Color.BLACK);
} else if (gumb.getBackground() == Color.BLACK){
gumb.setBackground(Color.WHITE);
}
if( gumb.getBackground() == Color.WHITE && gumb.getText() == "3"){
st -= 1;
} else if (gumb.getBackground() == Color.BLACK && gumb.getText() == "3"){
st += 1;
gumbi[0][0].setText("" + st);
}
}
}
The problem is that you created a copy of the Static Variable(Start.a) to the instance variable (st), which will be individual copy for each instance of action listener.
If you really need to maintain the value at class level , why not manipulate the value directly rather keeping a copy.
if( gumb.getBackground() == Color.WHITE && gumb.getText() == "3"){
Start.a -= 1;
} else if (gumb.getBackground() == Color.BLACK && gumb.getText() == "3"){
Start.a += 1;
gumbi[0][0].setText("" + st);
}
Your line
int st = Start.a;
isn't doing what you think. It's reading the value of a when the instance is created, and copying its value into a new variable st. Changing st won't have any effect on a because you're only changing a copy; and you've got a new copy for each instance that you create.
Try changing Start.a directly, rather than copying it into a new st and changing that.
Related
Here's my code that I have so far.
import java.util.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.Component;
public class MAIN {
public static void main(String[] args) {
String grade = null, sub = null;
int x = 0;
ALevel[] array = new ALevel[3];
for (x = 0; x < 3; x++) {
JFrame frame = new JFrame("COURSE CHECKER");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocation(430, 100);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.add(panel);
JLabel lbl = new JLabel("Select your subject(s):");
lbl.setAlignmentX(Component.CENTER_ALIGNMENT);
//lbl.setVisible(true);
panel.add(lbl);
//define items in a String array
String[] choices = { "MATHEMATICS", "FURTHER MATHEMATICS", "ACCOUNTING", "ECONOMICS",
"MANAGEMENT OF BUSINESS", "COMPUTER STUDIES", "PHYSICS", "CHEMISTRY",
"BIOLOGY", "DESIGN & TECHNOLOGY", "GEOGRAPHY"};
//create combobox/dropdown with the fixed array
final JComboBox<String> cb = new JComboBox<String>(choices);
cb.setMaximumSize(cb.getPreferredSize());
cb.setAlignmentX(Component.CENTER_ALIGNMENT);
//cb.setVisible(true);
panel.add(cb);
frame.setVisible(true);
array[x] = new ALevel(grade, sub);
array[x].gradecheck(sub, array[x].getaGrade());
}
cb.addActionListener(new ActionListener(){
public void actionPerformed(Action e){
String data = "Subject Selected: " + cb.getItemAt(cb.getSelectedIndex());
lbl.setText(data);
}
};
JLabel lbl1 = new JLabel("Select your grades");
lbl1.setAlignmentX(Component.CENTER_ALIGNMENT);
//lbl.setVisible(true);
panel.add(lbl1);
//define items in a String array
String[] choices1 = { "A", "B", "C", "D", "E"};
//create combobox/dropdown with the fixed array
final JComboBox<String> cb1 = new JComboBox<String>(choices1);
cb1.setMaximumSize(cb1.getPreferredSize());
cb1.setAlignmentX(Component.CENTER_ALIGNMENT);
//cb.setVisible(true);
panel.add(cb1);
JButton btn1 = new JButton("OK");
btn1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(btn1);
frame.setVisible(true);
for (x = 0; x < 3; x++) {
System.out.println("\nSubject: " + array[x].getaSub() + "\nGrade:" + array[x].getaGrade());
}
System.out.println("\nPoint: " + array[0].getaScore());
//
Scanner input = new Scanner(System.in);
String grade = null, sub = null;
int x = 0;
ALevel[] array = new ALevel[3];
for (x = 0; x < 3; x++) {
System.out.print("Enter subject: ");
sub = input.nextLine();
System.out.print("Enter grade: ");
grade = input.nextLine();
array[x] = new ALevel(grade, sub);
array[x].gradecheck(sub, array[x].getaGrade());
}
for (x = 0; x < 3; x++) {
System.out.println("\nSubject: " + array[x].getaSub() + "\nGrade:" + array[x].getaGrade());
}
System.out.println("\nPoint: " + array[0].getaScore());
System.out.println("You are eligible for: ");
for (x = 0; x < 3; x++) {
if (array[x].getSubjects() == 3) {
if (array[x].isMathcheck() == true && array[x].getSubscoreE() >= 3 && array[x].getaScore() >= 200) {
array[x].SCI();
}
if (array[x].getSubscoreE() >= 3 && array[x].getaScore() >= 200) {
array[x].SOB();
}
if (array[x].isMathcheck() == true && array[x].getSubscoreS() >= 2 && array[x].getaScore() >= 240) {
array[x].CEPA();
}
if (array[x].isMathcheck() == true && array[x].isPhyscheck() == true && array[x].getSubscoreS() >= 2
&& array[x].getaScore() >= 220) {
array[x].E3PA();
}
if (array[x].isMathcheck() == true && array[x].isPhyscheck() == true && array[x].isChemcheck() == true
&& array[x].getaScore() >= 240) {
array[x].PCEPA();
}
if (array[x].isMathcheck() == true && array[x].isPhyscheck() == true && array[x].getSubscoreS() >= 2
&& array[x].getaScore() >= 240) {
array[x].MEPA();
}
}
if (array[x].getSubjects() == 2) {
if (array[x].isMathcheck() == true && array[x].getSubscoreE() >= 2 && array[x].getaScore() >= 180) {
array[x].SCI();
}
if (array[x].getSubscoreE() >= 2 && array[x].getaScore() >= 180) {
array[x].SOB();
}
if (array[x].isMathcheck() == true && array[x].isPhyscheck() == true && array[x].getaScore() >= 180) {
array[x].E3PA();
}
if (array[x].isMathcheck() == true && array[x].isPhyscheck() == true && array[x].getaScore() >= 180) {
array[x].MEPA();
}
}
if (array[x].getaScore() < 180) {
System.out.print("None");
}
System.exit(0);
}//
}
}
the codings work well without the combobox and the data are dsiplayed in the console tab.
I want to make it easier by choosing data from combobox rather than enter input.
So, how do i display the selected item from the combobox?
You need to get the "selected item" from the combobox.
Then you can update your label, text area, or whatever else with the data it grabbed from your combobox.
JComboBox cb = (JComboBox)e.getSource();
String myName = (String)cb.getSelectedItem();
updateLabel(myName);
Note the cb.getSelectedItem(). That's what's actually grabbing the data from the combobox.
And here's a good resource with some more info about using Java comboboxes: https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
Ok guys...I'm stumped again.
I managed to get the game working. However, now I'm down to the point of trying to code the win conditions. I'm thinking of using a boolean array for each of the buttons, but can't figure out how to cross reference the buttons[] to the gameSquares[] to set the elements of gameSquares[] to true/false flags.
Any pointers? (Code is copied below).
** A few other interesting bugs I feel worth mentioning:
1) Start and Reset don't seem to work correctly
2) When the computer tries multiple attempts in invalid squares, the squares seem to jump or dance around. It's really weird.
package tictactoegame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class TicTacToeBoard extends JFrame implements ActionListener
{
JButton[] buttons = new JButton[10];
boolean player1 = false, player2 = false;
boolean[] gameSquares = {false, false, false,
false, false, false,
false, false, false};
boolean startPlayer = false;
int turnCount = 0;
public TicTacToeBoard()
{
JFrame gameWindow = new JFrame();
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(300,400);
gameWindow.setVisible(true);
JPanel gamePanel = new JPanel();
gamePanel.setSize(300,400);
GridLayout grid = new GridLayout(4,3);
gamePanel.setLayout(grid);
for(int i = 0; i < 9; i++)
{
buttons[i] = new JButton("");
buttons[i].addActionListener(this);
gamePanel.add(buttons[i]);
}
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this);
JButton helpButton = new JButton("Help");
helpButton.addActionListener(this);
gamePanel.add(startButton);
gamePanel.add(helpButton);
gamePanel.add(resetButton);
gameWindow.add(gamePanel);
gameWindow.pack();
while (turnCount < 9)
{
gamePlay();
}
}
public void gamePlay()
{
while(!startPlayer)
{
int random = randomGenerator();
if (random%2 == 0)
{
player1 = true;
JOptionPane.showMessageDialog(null, "Player is first.");
startPlayer = true;
}
else if (random%2 == 1)
{
player2 = true;
JOptionPane.showMessageDialog(null, "Computer is first.");
startPlayer = true;
}
}
if (player2)
{
int index;
Random randomGenerator = new Random();
index = randomGenerator.nextInt(9);
buttons[index].doClick();
player2 = false;
player1 = true;
}
}
public int randomGenerator()
{
int randomNum;
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(100);
return randomNum;
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source instanceof JButton)
{
JButton button = (JButton) source;
if (button.getText() == "Start")
{
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Reset")
{
for(int i = 0; i < 9; i++)
{
buttons[i].setText("");
}
startPlayer = false;
player1 = false;
player2 = false;
gamePlay();
}
else if (button.getText() == "Help")
{
JOptionPane.showMessageDialog(null, "Help:\n\n" +
"How to play-\n" +
"Select an empty square. The square will be filled with"
+ "with your symbole, either X or O.\n" +
"The game is won when either player gets three X's or"
+ "O's in a row horizontally,\n vertically, or diagonally.");
}
if (button.getText() == "" && player1)
{
button.setText("X");
turnCount += 1;
player1 = false;
player2 = true;
}
else if (button.getText() == "" && player2)
{
button.setText("O");
turnCount+=1;
player2 = false;
player1 = true;
}
else if (button.getText() == "X" || button.getText() == "O")
{
if(player2 == true)
{
gamePlay();
}
else
{
JOptionPane.showMessageDialog(null, "Invalid choice. Select"
+ " another square.");
}
}
}
}
}
Check this TicTacToe Full code using the Applets...:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
<applet code="TicTacToe.class" width="300" height="300">
</applet>
*/
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();
public void init() {
CURRENT_PLAYER = PLAYER1;
lbl.setText(CURRENT_PLAYER + " Turn!");
setLayout(new BorderLayout());
Panel p = new Panel();
GridLayout gl = new GridLayout(3, 3);
p.setLayout(gl);
setBackground(Color.BLACK);
setForeground(Color.WHITE);
setSize(300, 300);
Font myFont = new Font("TimesRoman", Font.BOLD, 80);
for (int i = 0; i < 9; i++) {
btnarray[i] = new Button(null);
btnarray[i].setActionCommand("" + i);
btnarray[i].addActionListener(this);
btnarray[i].setFont(myFont);
btnarray[i].setBackground(Color.white);
p.add(btnarray[i]);
}
add(BorderLayout.CENTER, p);
add(BorderLayout.NORTH, lbl);
add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int index = Integer.parseInt(e.getActionCommand());
btnarray[index].disable();
if (CURRENT_PLAYER == PLAYER1) {
btnarray[index].setLabel("X");
CURRENT_PLAYER = PLAYER2;
} else {
btnarray[index].setLabel("0");
CURRENT_PLAYER = PLAYER1;
}
lbl.setText(CURRENT_PLAYER + " Turn!");
check();
}
void check() {
String[] pattern = new String[8];
pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
+ btnarray[2].getLabel();
pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
+ btnarray[5].getLabel();
pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
+ btnarray[8].getLabel();
pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
+ btnarray[6].getLabel();
pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
+ btnarray[7].getLabel();
pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
+ btnarray[8].getLabel();
pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
+ btnarray[8].getLabel();
pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
+ btnarray[6].getLabel();
int j = 0;
while (j < 8) {
char[] array = pattern[j].toCharArray();
if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
lbl.setText(PLAYER1 + " Wins!");
} else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
lbl.setText(PLAYER2 + " Wins!");
}
j++;
}
}
}
I'm creating a GUI calculator, using FlowLayout, GridLayout and BorderLayout. I have the following code.
import java.awt.*;
import javax.swing.*;
//Imports visual components for program
import java.awt.event.*;
//Imports functions for providing performing action on object
public class Calc extends JFrame implements ActionListener {
JPanel[] row = new JPanel[5];
//5 panels are created for 5 rows of buttons
JButton[] button = new JButton[19];
String[] buttonString = {"1","2","3","+","4","5","6","-",
"7","8","9","*",".","/","C","rt","%",
"=", "0"};
double[] temporary = {0,0};
//Two memory locations for current number and upcoming number for signs such as *,/,%,+,-
boolean[] sign = new boolean[5];
//5 values for +,-,*,/,% are stored in array because they expect another number upon invocation
JTextArea display = new JTextArea(1,10);
//Creates display with location specified
Calc(){
//Constructor begins here
setResizable(false);
//Sets calculator size to be fixed at 380x250
//5x5 is created and selected for the calculator
for(int a = 0; a < 5; a++)
sign[a] = false;
//Initialises the state of the signs for +,-,*,/,%
JPanel displaypanel = new JPanel();
JPanel first = new JPanel();
JPanel last = new JPanel();
//Create three panels for buttons to be placed in
displaypanel.setLayout(new FlowLayout());
displaypanel.add(display);
//Display is added
first.setLayout(new GridLayout(3,5));
for(int a = 0; a<15; a++)
first.add(button[a]);
//"first" panel is added
last.setLayout(new GridLayout(1,4));
last.add(button[15]);
last.add(button[16]);
last.add(button[17]);
last.add(button[18]);
JFrame window = new JFrame("Task twelve");
window.setLayout(new BorderLayout());
window.add(displaypanel, BorderLayout.PAGE_START);
window.add(first, BorderLayout.CENTER);
window.add(last, BorderLayout.PAGE_END);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);
for(int a = 0; a < 19; a++){
button[a] = new JButton();
button[a].setText(buttonString[a]);
button[a].addActionListener(this);
//Assigns all the numbers and signs for the buttons
}
for(int a = 0; a < 5; a++)
row[a] = new JPanel();
//Initialises JPanel for rows so they can be used
//Assigns size for all buttons and display
display.setEditable(false);
}
public void clear(){
try{
display.setText("");
//Sets the display to be blank
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false
temporary[0] = 0;
temporary[1] = 0;
//Sets temporary values to be 0 as well
} catch(NullPointerException e){
}
}
public void root(){
try{
double temp = Math.sqrt(Double.parseDouble(display.getText()));
//Creates variable that converts the value in display to a double and Sqroots the value
display.setText(Double.toString(temp));
//Converts value in temp to string and copies it to display
} catch(NullPointerException e){
}
}
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp2 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp2[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp3 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp3[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(sign[0] == true)
//Addition sign
result = temporary[0] + temporary[1];
else if(sign[1] == true)
//Subtraction sign
result = temporary[0] - temporary[1];
else if(sign[2] == true)
//Multiplication sign
result = temporary[0] * temporary[1];
else if(sign[3] == true)
//Division sign
result = temporary[0] / temporary[1];
else if(sign[4] == true)
//Modulus sign
result = temporary[0] % temporary[1];
display.setText(Double.toString(result));
for(int a = 0; a < 5; a++)
sign[a] = false;
//Sets state of all signs to be false after one of them has been invoked
} catch(NumberFormatException e) {
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == button[0])
display.append("1");
//When "1" is pressed, "1" is inserted to the display
if(ae.getSource() == button[1])
display.append("2");
if(ae.getSource() == button[2])
display.append("3");
if(ae.getSource() == button[3]){
//Addition sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]){
//Subtraction sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("7");
if(ae.getSource() == button[9])
display.append("8");
if(ae.getSource() == button[10])
display.append("9");
if(ae.getSource() == button[11]){
//Multiplication sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]){
//Division sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
root();
if(ae.getSource() == button[16]){
//Modulus sign is selected
temporary[0] = Double.parseDouble(display.getText());
sign[4] = true;
display.setText("");
}
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}
public static void main(String[] args){
Calc c = new Calc();
}
}
Compiling this doesn't result in any errors. However, running the class does.
Exception in thread"main" java.lang.NullPointerException
at java.awt.Container.addlmpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Calc.<init>(Calc.java:43)
at Calc.main(Calc.java:198)
I don't understand these errors so I do not know how to fix this. Can anyone help?
You are creating 15 buttons in the loop button[a] = new JButton(buttonString[a]); but then you are asking for button[15, 16, ...] (the 16nth, 17nth... button you have not created) and are null.
So My problem is that the applet lunches with nothing in it as soon as i hover the mouse
on top of the buttons it displays them and works perfectly afterwards. I think there might be something wrong with paint but i am not sure. I tried several changes but noting seems to work.
Any help will be much appreciated.
-- Rafael
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class poker extends JApplet implements ActionListener, ListSelectionListener {
private DefaultListModel listModel = new DefaultListModel();
JList jList = new JList(listModel);
JButton dealButton = new JButton("Deal");
JButton quitButton = new JButton("Quit");
JButton finishButton = new JButton("finish");
JPanel panel = new JPanel();
JPanel jPanel = new JPanel();
JPanel lPanel = new JPanel();
JLabel label = new JLabel();
JLabel balance = new JLabel();
private String displayDeal = null;
private String displayFinish = null;
private poker.Card deck[];
private int currentCard;
private double money = 0;
private poker.Card hand[];
private boolean nothing;
private boolean pair;
private boolean twoPair;
private boolean threeKind;
private boolean fourKind;
private boolean fullHouse;
private boolean flush;
private boolean straight;
private boolean royalStraight;
private boolean straightFlush;
private boolean RoyalFlush;
String faces[] = {"Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King", "Ace"};
String suits[] = {"Hearts", "Diamonds", "Clubs", "Spades"};
#Override
public void init() {
this.setSize(500, 500);
this.setLayout(new BorderLayout());
jList.addListSelectionListener(this);
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
hand = new poker.Card[5];
deck = new poker.Card[52];
currentCard = -1;
for (int i = 0; i < deck.length; i++) {
deck[i] = new poker.Card(faces[i % 13], suits[i / 13]);
}
listModel.setSize(5);
dealButton.addActionListener(this);
finishButton.addActionListener(this);
quitButton.addActionListener(this);
finishButton.setEnabled(false);
panel.add(dealButton);
panel.add(finishButton);
panel.add(quitButton);
panel.add(label);
jPanel.add(jList);
add(balance, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
add(jPanel, BorderLayout.NORTH);
setVisible(true);
}
class Card {
#Override
public String toString() {
return face + " of " + suit + "\n";
}
public String getFace() {
return face;
}
public String getSuit() {
return suit;
}
private String face;
private String suit;
public Card(String s, String s1) {
face = s;
suit = s1;
}
}
#Override
public void valueChanged(ListSelectionEvent event) {
int[] indices = jList.getSelectedIndices();
if (indices.length > 4) {
JOptionPane.showMessageDialog(null, "You may only select four "
+ "cards.");
jList.clearSelection();
}
}
#Override
public void actionPerformed(ActionEvent event) {
poker.Card card = null;
if (event.getSource() == dealButton) {////////////////////////////
finishButton.setEnabled(true);
dealButton.setEnabled(false);
label.setText(null);
shuffle();// reset deck
for (int j = 0; j < 5; j++) {
card = dealCard();
hand[j] = card;
listModel.setElementAt(hand[j], j);
}
if (money < -1000) {
JOptionPane.showMessageDialog(null, "GAME OVER. You have no "
+ "more money. ");
System.exit(0);
}
//evaluate();
label.setText(displayDeal);
displayDeal = null;
} else if (event.getSource() == finishButton) {///////////////////////
dealButton.setEnabled(true);
finishButton.setEnabled(false);
int c = 5; //to get new card from deck
int maxIndex = jList.getMaxSelectionIndex();
for (int l = 0; l <= maxIndex; l++) {
if (jList.isSelectedIndex(l)) {
listModel.removeElementAt(l);
listModel.add(l, deck[c]);
c++;
}
}
jList.revalidate();
jPanel.repaint();
evaluate();
giveMoney();
label.setText(displayFinish);
balance.setHorizontalAlignment(SwingConstants.CENTER);
balance.setText("Money: $" + money );
jList.clearSelection();
displayFinish = null;
} else if (event.getSource() == quitButton) {///////////////////////
label.setText(null);
balance.setHorizontalAlignment(SwingConstants.CENTER);
balance.setText("You have won $" + money + " dollars.");
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit?", "User Confirmation",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
dealButton.setEnabled(false);
finishButton.setEnabled(false);
quitButton.setEnabled(false);
System.exit(0);
}
}
this.setVisible(true);
this.validate();
}
// giveMoney() keeps track of the money.
public void giveMoney() {
if (nothing) {
money += -20.00;
nothing = false;
}
if (pair) {
money += 50.00;
pair = false;
}
if (twoPair) {
money += 100.00;
twoPair = false;
}
if (threeKind) {
money += 150.00;
threeKind = false;
}
if (straight) {
money += 200.00;
straight = false;
}
if (royalStraight) {
money += 200.00;
royalStraight = false;
}
if (flush) {
money += 250.00;
flush = false;
}
if (fullHouse) {
money += 300;
}
if (fourKind) {
money += 400.00;
fourKind = false;
}
if (straightFlush) {
money += 500.00;
straightFlush = false;
}
if (RoyalFlush) {
money += 1000.00;
RoyalFlush = false;
}
this.validate();
}
// populates deck array
public void shuffle() {
currentCard = -1;
for (int i = 0; i < deck.length; i++) {
int j = (int) (Math.random() * 52D);
poker.Card card = deck[i];
deck[i] = deck[j];
deck[j] = card;
}
this.validate();
}
public poker.Card dealCard() {
if (++currentCard < deck.length) {
return deck[currentCard];
} else {
dealButton.setEnabled(false);
return null;
}
}
public void evaluate() {
int i = 0;
String setOf = null;
nothing = false; pair = false; twoPair = false; threeKind = false;
straight = false; royalStraight = false; flush = false;
fullHouse = false; fourKind = false; straightFlush = false;
RoyalFlush = false;
if (hand[0].getSuit().equals(hand[1].getSuit())
&& hand[1].getSuit().equals(hand[2].getSuit())
&& hand[2].getSuit().equals(hand[3].getSuit())
&& hand[3].getSuit().equals(hand[4].getSuit())) {
flush = true;
displayDeal = "You have a flush";
displayFinish = "Flush. Win $250.00 dollars.";
}
if (sort2(hand) && !royalStraight) {
straight = true;
displayDeal = "You have a straight";
displayFinish = "Straight. Win $200.00 dollars.";
}
if (straight && flush) {
straightFlush = true;
straight = false;
flush = false;
displayDeal = "You have a straight Flush";
displayFinish = "straight Flush. Win $500.00 dollars.";
}
if (straightFlush) {
for (int j = 9; j < 13; j++) {
if (hand[i].getFace().equals(faces[j])
&& hand[i + 1].getFace().equals(faces[j])
&& hand[i + 2].getFace().equals(faces[j])
&& hand[i + 3].getFace().equals(faces[j])
&& hand[i + 4].getFace().equals(faces[j])) {
straightFlush = false;
RoyalFlush = true;
displayDeal = "You have a royal Flush";
displayFinish = "Royal Flush. Win $1000.00 dollars.";
}
}
}
if (straight) {
for (int j = 9; j < 13; j++) {
if (hand[i].getFace().equals(faces[j])
&& hand[i + 1].getFace().equals(faces[j])
&& hand[i + 2].getFace().equals(faces[j])
&& hand[i + 3].getFace().equals(faces[j])
&& hand[i + 4].getFace().equals(faces[j])) {
straight = false;
royalStraight = true;
displayDeal = "You have a royal straight";
displayFinish = "royal Straight. Win $200.00 dollars.";
}
}
}
if (hand[0].getFace().equals(hand[1].getFace())
&& hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[1].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
&& hand[0].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
&& hand[0].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[4].getFace())) {
fourKind = true;
displayDeal = "You have a four of a kind";
displayFinish = "Four of a kind. Win $400.00 dollars.";
} else if (hand[0].getFace().equals(hand[1].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[4].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[0].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[1].getFace().equals(hand[4].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[4].getFace()) && !fullHouse) {
twoPair = true;
displayDeal = "You have two pairs. ";
displayFinish = "Two Pairs. Win $100.00 dollars.";
} else if (hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[3].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[3].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
|| hand[2].getFace().equals(hand[3].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
&& hand[0].getFace().equals(hand[1].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[3].getFace())
&& hand[0].getFace().equals(hand[4].getFace()) && !straightFlush) {
fullHouse = true;
displayDeal = "You have a full house.";
displayFinish = "Full House. Win $300.00 dollars.";
}
if ((hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[2].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[2].getFace())
&& hand[0].getFace().equals(hand[3].getFace())
|| hand[1].getFace().equals(hand[3].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[3].getFace())
|| hand[0].getFace().equals(hand[1].getFace())
&& hand[1].getFace().equals(hand[4].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[4].getFace())
|| hand[2].getFace().equals(hand[3].getFace())
&& hand[3].getFace().equals(hand[4].getFace())
|| hand[1].getFace().equals(hand[2].getFace())
&& hand[2].getFace().equals(hand[3].getFace()))
&& !twoPair && !fullHouse && !fourKind) {
threeKind = true;
displayDeal = "You have three of a kind of " + setOf + "s.";
displayFinish = "three of a kind of " + setOf + "s. Win $150.00 dollars.";
} else if ((hand[i].getFace().equals(hand[i + 1].getFace())
|| hand[i].getFace().equals(hand[i + 2].getFace())
|| hand[i].getFace().equals(hand[i + 3].getFace())
|| hand[i].getFace().equals(hand[i + 4].getFace())
|| hand[i + 1].getFace().equals(hand[i + 2].getFace())
|| hand[i + 1].getFace().equals(hand[i + 3].getFace())
|| hand[i + 1].getFace().equals(hand[i + 4].getFace())
|| hand[i + 2].getFace().equals(hand[i + 3].getFace())
|| hand[i + 2].getFace().equals(hand[i + 4].getFace())
|| hand[i + 3].getFace().equals(hand[4].getFace()))
&& !twoPair && !threeKind && !fullHouse) {
pair = true;
displayDeal = "You have a pair of " + setOf + "s.";
displayFinish = "Pair of " + setOf + "s. Win $50.00 dollars.";
}
if (!pair && !twoPair && !threeKind && !fullHouse && !fourKind
&& !straight && !flush && !straightFlush && !RoyalFlush
&& !royalStraight) {
nothing = true;
displayDeal = "You have nothing.";
displayFinish = "Nothing. Lose 20.00 dollars.";
}
this.validate();
}
public int getFaceValue2(poker.Card card) {
String s = card.getFace();
byte byte0 = 0;
if (s.equals(faces[0])) {
byte0 = 2;
}
if (s.equals(faces[1])) {
byte0 = 3;
}
if (s.equals(faces[2])) {
byte0 = 4;
}
if (s.equals(faces[3])) {
byte0 = 5;
}
if (s.equals(faces[4])) {
byte0 = 6;
}
if (s.equals(faces[5])) {
byte0 = 7;
}
if (s.equals(faces[6])) {
byte0 = 8;
}
if (s.equals(faces[7])) {
byte0 = 9;
}
if (s.equals(faces[8])) {
byte0 = 10;
}
if (s.equals(faces[9])) {
byte0 = 11;
}
if (s.equals(faces[10])) {
byte0 = 12;
}
if (s.equals(faces[11])) {
byte0 = 13;
}
if (s.equals(faces[12])) {
byte0 = 14;
}
return byte0;
}
public boolean sort2(poker.Card acard[]) {
boolean flag = false;
int ai[] = new int[5];
for (int i = 0; i < 5; i++) {
ai[i] = getFaceValue2(acard[i]);
}
for (int k = 1; k < ai.length; k++) {
for (int l = 0; l < ai.length - 1; l++) {
if (ai[l] > ai[l + 1]) {
int j = ai[l];
ai[l] = ai[l + 1];
ai[l + 1] = j;
}
}
}
for (int i1 = 0; i1 < ai.length - 1; i1++) {
if (ai[0] + 1 == ai[1] && ai[1] + 1 == ai[2] && ai[2] + 1
== ai[3] && ai[3] + 1 == ai[4]) {
flag = true;
} else {
flag = false;
}
}
if (flag) {
System.out.print(hand[0] + " " + hand[1] + " " + hand[2] + " "
+ hand[3] + " " + hand[4]);
}
System.out.print(ai[0] + " " + ai[1] + " " + ai[2] + " " + ai[3]
+ " " + ai[4]);
return flag;
}
}
When i run this applet using eclipse, it runs fine and i can see 2 buttons. Have you tried validating the applet after everything is ready?
this.validate();
this.repaint();
from Container.class:
The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
I took sometime to modify the code of yours and I removed the paint() method and its working, now the screen display's without any freezing and all the components are displayed. Here's one important information for you which i found regarding paint() method when you extend JApplet.
Note: Move the logic which you had in your paint() method according to your design.
However, JApplets have a lot of extra structure that plain Applets
don't have. Because of this structure, the painting of a JApplet is a
more complex affair and is handled by the system. So, when you make a
subclass of JApplet you should not write a paint() method for it. As
we will see, if you want to draw on a JApplet, you should add a
component to the applet to be used for that purpose. On the other
hand, you can and generally should write an init() method for a
subclass of JApplet.
Below is the modified code, Hope it helps!!!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Poker extends JApplet implements ActionListener, ListSelectionListener {
private DefaultListModel listModel = new DefaultListModel();
JList jList = new JList(listModel);
JButton dealButton = new JButton("Deal card");
JButton quitButton = new JButton("Quit");
JButton finishButton = new JButton("finish");
JPanel panel = new JPanel();
JPanel jPanel = new JPanel();
private Poker.Card deck[];
private int currentCard;
private int money;
String faces[] = {
"Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Jack",
"Queen", "King", "Ace"
};
String suits[] = {
"Hearts", "Diamonds", "Clubs", "Spades"
};
private boolean card1State;
private boolean card2State;
private boolean card3State;
private boolean card4State;
private boolean card5State;
private Poker.Card hand[];
private boolean pressed;
private boolean nothing;
private boolean pair;
private boolean twoPair;
private boolean threeKind;
private boolean fourKind;
private boolean fullHouse;
private boolean flush;
private boolean straight;
private boolean royalStraight;
private boolean straightFlush;
private boolean RoyalFlush;
private final int ROYALFLUSH = 8;
private int value;
private boolean firstDeal;
#Override
public void init(){
this.setSize(500, 500);
jList.addListSelectionListener(this);
jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
hand = new Poker.Card[5];
deck = new Poker.Card[52];
currentCard = -1;
for(int i = 0; i < deck.length; i++)
deck[i] = new Poker.Card(faces[i % 13], suits[i / 13]);
listModel.setSize(5);
dealButton.addActionListener(this);
finishButton.addActionListener(this);
quitButton.addActionListener(this);
finishButton.setEnabled(false);
// c.setLayout(new FlowLayout());
panel.add(dealButton);
panel.add(finishButton);
panel.add(quitButton);
add(panel, BorderLayout.SOUTH);
jPanel.add(jList);
add(jPanel, BorderLayout.NORTH);
setVisible(true);
}
class Card
{
#Override
public String toString()
{
return face + " of " + suit + "\n";
}
public String getFace()
{
return face;
}
public String getSuit()
{
return suit;
}
private String face;
private String suit;
public Card(String s, String s1)
{
face = s;
suit = s1;
}
}
#Override
public void valueChanged(ListSelectionEvent event) {
JList source = (JList) event.getSource();
java.util.List values = source.getSelectedValuesList();
listModel.removeElement(values);
changeCards();
}
#Override
public void actionPerformed(ActionEvent event) {
Poker.Card card = null;
int i = 5;
if(event.getSource() == dealButton){
pressed = true;
dealButton.setEnabled(false);
finishButton.setEnabled(true);
for(int j = 0; j < 5; j++){
card = dealCard();
hand[j] = card;
listModel.setElementAt(hand[j], j);
}
if(money < -1000){
JOptionPane.showMessageDialog(null, "GAME OVER. ");
System.exit(0);
}
}else if( event.getSource() == finishButton){
// still needs implementation
} else if (event.getSource() == quitButton) {
pressed = true;
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit?", "User Confirmation",
JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
dealButton.setEnabled(false);
finishButton.setEnabled(false);
quitButton.setEnabled(false);
System.exit(0);
}
}
this.setVisible(true);
this.validate();
}
public void giveMoney() {
if (nothing)
{ money -= 20;
}
if (pair) {
money += 50;
}
if (twoPair) {
money += 100;
}
if (threeKind) {
money += 150;
}
if (straight) {
money += 200;
}
if (royalStraight)
{
money += 200;
}
if (flush) {
money += 250;
}
if (fullHouse) {
money += 300;
}
if (fourKind)
{
money += 400;
}
if (straightFlush) {
money += 500;
}
if (RoyalFlush) {
money += 1000;
}
}
public void shuffle() {
for (int i = 0; i < deck.length; i++) {
int j = (int) (Math.random() * 52D);
Poker.Card card = deck[i];
deck[i] = deck[j];
deck[j] = card;
}
dealButton.setEnabled(true);
this.validate();
}
public Poker.Card dealCard() {
if (++currentCard < deck.length) {
return deck[currentCard];
} else {
dealButton.setEnabled(false);
return null;
}
}
// public void paint(Graphics g){
//
// this.setBackground(Color.gray);
// Font font = new Font("Italic", 3, 14);
// g.setFont(font);
// if(pressed)
// {
// Font font1 = new Font("Card", 1, 24);
// g.setFont(font1);
//
// if(nothing)
// g.drawString("You got nothing!! You lose $20 ", 50, 125);
// if(pair)
// g.drawString("A pair!! Win $50 ", 50, 125);
// if(twoPair)
// g.drawString("Two pair!! win $100 ", 50, 125);
// if(threeKind)
// g.drawString("Three of a Kind!! Win $150 ", 50, 125);
// if(straight)
// g.drawString("A Straight!! Win $200 ", 50, 125);
// if (royalStraight)
// g.drawString("A Royal Straight!! Win $200 ", 50, 125);
// if(flush)
// g.drawString("A Flush!! Win $250 ", 50, 125);
// if(fullHouse)
// g.drawString("A Full House!! Win $300 ", 50, 125);
// if(straightFlush)
// g.drawString("A Straight Flush!! Win $500 ", 50, 125);
// if(RoyalFlush)
// g.drawString("A Royal Flush!! Win $100 ", 50, 125);
// }
//
// this.setVisible(true);
// }
public void changeCards(){
System.out.println("change cards");
firstDeal = true;
Object obj = null;
if(!card1State)
{
Poker.Card card = dealCard();
hand[0] = card;
}
if(!card2State)
{
Poker.Card card6 = dealCard();
hand[1] = card6;
}
if(!card3State)
{
Poker.Card card7 = dealCard();
hand[2] = card7;
}
if(!card4State)
{
Poker.Card card8 = dealCard();
hand[3] = card8;
}
if(!card5State)
{
Poker.Card card9 = dealCard();
hand[4] = card9;
}
}
public void evaluate() {
int i = 0;
if(hand[0].getSuit().equals(hand[1].getSuit()) &&
hand[1].getSuit().equals(hand[2].getSuit()) &&
hand[2].getSuit().equals(hand[3].getSuit()) &&
hand[3].getSuit().equals(hand[4].getSuit()))
{
flush = true;
if (flush == true)
System.out.println("you got a a flush");
}
if(sort2(hand)){
straight = true;
if (straight = true)
System.out.println("you got a a straight");
}
if(straight && flush)
{
straightFlush = true;
straight = false;
flush = false;
System.out.println("you got a straight flush");
}
if(straightFlush)
{
for(int j = 9; j < 13; j++)
if(hand[i].getFace().equals(faces[j]) &&
hand[i + 1].getFace().equals(faces[j + 1]) &&
hand[i + 2].getFace().equals(faces[j + 2]) &&
hand[i + 3].getFace().equals(faces[j + 3]) &&
hand[i + 4].getFace().equals(faces[j + 4]))
{
straightFlush = false;
RoyalFlush = true;
}
}
if(hand[0].getFace().equals(hand[1].getFace()) &&
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[1].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()))
fourKind = true;
else
if(hand[0].getFace().equals(hand[1].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[4].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[0].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[1].getFace().equals(hand[4].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) && !fullHouse)
{
System.out.println("2 pair=true;");
twoPair = true;
} else
if(hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[3].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[3].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) ||
hand[2].getFace().equals(hand[3].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) &&
hand[0].getFace().equals(hand[1].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[3].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) && !straightFlush){
fullHouse = true;
}
if((hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[2].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[2].getFace()) &&
hand[0].getFace().equals(hand[3].getFace()) ||
hand[1].getFace().equals(hand[3].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[3].getFace()) ||
hand[0].getFace().equals(hand[1].getFace()) &&
hand[1].getFace().equals(hand[4].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[4].getFace()) ||
hand[2].getFace().equals(hand[3].getFace()) &&
hand[3].getFace().equals(hand[4].getFace()) ||
hand[1].getFace().equals(hand[2].getFace()) &&
hand[2].getFace().equals(hand[3].getFace())) &&
!twoPair && !fullHouse && !fourKind){
threeKind = true;
}
else
if((hand[i].getFace().equals(hand[i + 1].getFace()) ||
hand[i].getFace().equals(hand[i + 2].getFace()) ||
hand[i].getFace().equals(hand[i + 3].getFace()) ||
hand[i].getFace().equals(hand[i + 4].getFace()) ||
hand[i + 1].getFace().equals(hand[i + 2].getFace()) ||
hand[i + 1].getFace().equals(hand[i + 3].getFace()) ||
hand[i + 1].getFace().equals(hand[i + 4].getFace()) ||
hand[i + 2].getFace().equals(hand[i + 3].getFace()) ||
hand[i + 2].getFace().equals(hand[i + 4].getFace()) ||
hand[i + 3].getFace().equals(hand[4].getFace())) &&
!twoPair && !threeKind && !fullHouse){
pair = true;
}
else
{ nothing = true;
System.out.println("you got nothing");
}
this.validate();
// giveMoney();
}
public int getFaceValue2( Poker.Card card) {
String s = card.getFace();
byte byte0 = 0;
if(s.equals(faces[0]))
byte0 = 2;
if(s.equals(faces[1]))
byte0 = 3;
if(s.equals(faces[2]))
byte0 = 4;
if(s.equals(faces[3]))
byte0 = 5;
if(s.equals(faces[4]))
byte0 = 6;
if(s.equals(faces[5]))
byte0 = 7;
if(s.equals(faces[6]))
byte0 = 8;
if(s.equals(faces[7]))
byte0 = 9;
if(s.equals(faces[8]))
byte0 = 10;
if(s.equals(faces[9]))
byte0 = 11;
if(s.equals(faces[10]))
byte0 = 12;
if(s.equals(faces[11]))
byte0 = 13;
if(s.equals(faces[12]))
byte0 = 14;
return byte0;
}
public boolean sort2( Poker.Card acard[]){
boolean flag = false;
int ai[] = new int[5];
for(int i = 0; i < 5; i++)
ai[i] = getFaceValue2(acard[i]);
for(int k = 1; k < ai.length; k++)
{
for(int l = 0; l < ai.length - 1; l++)
if(ai[l] > ai[l + 1])
{
int j = ai[l];
ai[l] = ai[l + 1];
ai[l + 1] = j;
}
}
for(int i1 = 0; i1 < ai.length - 1; i1++)
if(ai[0] + 1 == ai[1] && ai[1] + 1 == ai[2] && ai[2] + 1 ==
ai[3] && ai[3] + 1 == ai[4])
flag = true;
else
flag = false;
if(flag)
System.out.print(hand[0] + " " + hand[1] + " " + hand[2] + " " +
hand[3] + " " + hand[4]);
System.out.print(ai[0] + " " + ai[1] + " " + ai[2] + " " + ai[3] +
" " + ai[4]);
return flag;
}
}
Okay everybody, I know the knight's tour problem is popular for all cs students and I am having trouble getting mine to work. I use this recursive algorithm to progress through the moves, however, once I get to around move 50 I have to backtrack since no moves are available and I end up never completing the tour. I pass a ChessNode (holds things like if node has been visited, move it was visited, etc...), next row, next column, and previous node's move count.
private int moveRecur(ChessNode current, int row, int column, int moveV){
current.moveVisited = moveV+1;
if(current.moveVisited > 63){
return 0;
}
if(current.position==13 && aboard[row-1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column+2], row-1, column+2, current.moveVisited);
}
else if(current.position==22 && aboard[row-2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column+1], row-2, column+1, current.moveVisited);
}
else if(current.position == 50 && aboard[row+1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column-2], row+1, column-2, current.moveVisited);
}
else if(current.position == 41 && aboard[row+2][column-1].visited != 1){
current.visited =1;
moveRecur(aboard[row+2][column-1], row+2, column-1, current.moveVisited);
}
else if(current.position == 46 && aboard[row+2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column+1], row+2, column+1, current.moveVisited);
}
else if(current.position == 53 && aboard[row+1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column+2], row+1, column+2, current.moveVisited);
}
else if(current.position == 10 && aboard[row-1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column-2], row-1, column-2, current.moveVisited);
}
else if (current.position == 17 && aboard[row-2][column-1].visited != 1){
current.visited =1;
moveRecur(aboard[row-2][column-1], row-2, column-2, current.moveVisited);
}
if(row+1>=0 && row+1<8 && column+2>=0 && column+2<8){
if(aboard[row+1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column+2], row+1, column+2, current.moveVisited);
}
}
if(row+2>=0 && row+2<8 && column+1>=0 && column+1<8){
if(aboard[row+2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column+1], row+2, column+1, current.moveVisited);
}
}
if(row-1>=0 && row-1<8 && column-2>=0 && column-2<8){
if(aboard[row-1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column-2], row-1, column-2, current.moveVisited);
}
}
if(row-2>=0 && row-2<8 && column-1>=0 && column-1<8){
if(aboard[row-2][column-1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column-1], row-2, column-1, current.moveVisited);
}
}
if(row+1>=0 && row+1<8 && column-2>=0 && column-2<8){
if(aboard[row+1][column-2].visited != 1){
current.visited = 1;
moveRecur(aboard[row+1][column-2], row+1, column-2, current.moveVisited);
}
}
if(row+2>=0 && row+2<8 && column-1>=0 && column-1<8){
if(aboard[row+2][column-1].visited != 1){
current.visited = 1;
moveRecur(aboard[row+2][column-1], row+2, column-1, current.moveVisited);
}
}
if(row-1>=0 && row-1<8 && column+2>=0 && column+2<8){
if(aboard[row-1][column+2].visited != 1){
current.visited = 1;
moveRecur(aboard[row-1][column+2], row-1, column+2, current.moveVisited);
}
}
if(row-2>=0 && row-2<8 && column+1>=0 && column+1<8){
if(aboard[row-2][column+1].visited != 1){
current.visited = 1;
moveRecur(aboard[row-2][column+1], row-2, column+1, current.moveVisited);
}
}
//System.out.println(current.position + " "+current.moveVisited);
current.visited = 0;
return 0;
}
So, initially I check for the spots that can move to the corner board positions, and then I just make recursive calls based on available moves. So I guess my main question is am I doing something wrong? or is there another condition I can used to make the tour a little more intuitive?
Thanks in advance!
This is the Knight's tour code in java and has a brilliant layout. I did this using backtracking using recursion. This was my class assignment. Do contact me if you have any problem understanding or running this code.
package knights.tour;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.*;
import javax.swing.*;
public class KnightsTour extends JFrame implements ActionListener{
//All the static variables used between action listeners and functions.
public static String path;
public static int btnPressed = 0;
public static int rowSelected;
public static String[] pathArray;
public static int[][] coordinatesArray;
public static int columnSelected;
public static int flag =0;
public static int increment = 0;
public static JPanel panel1 = new JPanel();
public static JPanel panel3 ;
public static JButton btnStart = new JButton("Start Animation");
public static JButton btnClear = new JButton("Clear");
public static JTextArea lblPath = new JTextArea();
public static JLabel lblStartRow = new JLabel();
public static JLabel lblStartColumn = new JLabel();
public static JButton[][] button;
public static int variableForIncrement=0;
static int row ;
static int column ;
static int[][] array = new int[row][column];
public static int count = 1;
KnightsTour(){
//Setting layout of the frame in the constructor and adding buttons to the panel and the frame.
getContentPane().setLayout(new GridLayout(2,1));
lblPath.setLineWrap(true);
lblPath.setColumns(10);
lblPath.setSize(700, 100);
lblPath.setEditable(false);
panel1.add(btnStart);
panel1.add(btnClear);
panel1.add(lblStartRow);
panel1.add(lblStartColumn);
panel1.add(lblPath);
panel3 = new JPanel(new GridLayout(row,column));
// Initializing Array of buttons for the user to click on the chess board.
button= new JButton[row][column];
array = new int[row][column];
coordinatesArray = new int[row*column][2]; // This array stores the coordinates as the Knight
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
button[i][j] = new JButton();
}
}
//Setting background of the buttons to black and white for chessboard layout.
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(i%2 ==j%2){
button[i][j].setBackground(Color.BLACK);
button[i][j].setForeground(Color.WHITE);
}
else{
button[i][j].setBackground(Color.WHITE);
}
panel3.add(button[i][j]);
button[i][j].addActionListener(this);
}
}
btnClear.addActionListener(this);
btnStart.addActionListener(this);
add(panel3);
add(panel1);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO code application logic here
String input =JOptionPane.showInputDialog("Enter the rows and columns in the format (row,column)");
String[] ar = input.split(",");
row = Integer.parseInt(ar[0]); // Finding out row and column from the user input.
column = Integer.parseInt(ar[1]);
pathArray = new String[row*column]; // This array is kept to store the path of the knight.
JFrame frame = new KnightsTour();
frame.setVisible(true);
frame.setSize(700,700);
}
//All the computation takes place in this function. It checks the neighbour and recursively calls itself.
public static void neighbourRecursion(int a,int b){
pathArray[increment] = Integer.toString(a) + "," + Integer.toString(b); // Storing the path of the Knight
increment++;
array[a][b] = count; //Stroing value of count.
button[a][b].setText(String.valueOf(count));
coordinatesArray[variableForIncrement][0] = button[a][b].getX(); //Finding coordinates of buttons to show animation
coordinatesArray[variableForIncrement][1] = button[a][b].getY();
count++;
variableForIncrement++;
//Checking for valid neighbours and calling itself recursively.
if(a <= row-3 && b<=column-2){
if(alreadyVisited(a+2,b+1)){
neighbourRecursion(a+2,b+1);
}
}
if(a<=row-3 && b>=1){
if(alreadyVisited(a+2,b-1)){
neighbourRecursion(a+2,b-1);
}
}
if(a>=2 && b<=column-2){
if(alreadyVisited(a-2,b+1)){
neighbourRecursion(a-2,b+1);
}
}
if(a>=2 && b>=1){
if(alreadyVisited(a-2,b-1)){
neighbourRecursion(a-2,b-1);
}
}
if(a<=row-2 && b>=2){
if(alreadyVisited(a+1,b-2)){
neighbourRecursion(a+1,b-2);
}
}
if(a<=row-2 && b<=column-3){
if(alreadyVisited(a+1,b+2)){
neighbourRecursion(a+1,b+2);
}
}
if(a>=1 && b>=2){
if(alreadyVisited(a-1,b-2)){
neighbourRecursion(a-1,b-2);
}
}
if(a>=1 && b <=column-3){
if(alreadyVisited(a-1,b+2)){
neighbourRecursion(a-1,b+2);
}
}
//Breaking condition of the function.
if(count == (row*column)+1){
}
// Backtracking condition if there is no neighbour.
else{
button[a][b].setText("");
array[a][b]=0;
count--;
variableForIncrement--;
if(increment >0){
increment--;
}
return ;
}
}
//This function checks if the neighbour is already visited.
public static boolean alreadyVisited(int a,int b){
if(array[a][b] != 0){
return false;
}
else{
return true;
}
}
#Override
public void actionPerformed(ActionEvent e) {
//when clear is pressed all arrays and global variables are set to initial conditon.
if(e.getSource() == btnClear){
for(int i =0;i<row;i++){
for(int j=0;j<column;j++){
array[i][j] = 0;
button[i][j].setText("");
count = 1;
lblPath.setText("");
lblStartRow.setText("");
lblStartColumn.setText("");
flag =0;
variableForIncrement=0;
increment =0;
path =" ";
}
}
}
//If start animation button is pressed animation is started.
else if(e.getSource() == btnStart){
animate();
}
// When the button is pressed.
else{
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(e.getSource() == button[i][j]){
if(flag == 1){
lblPath.setText(" Please press clear before clicking again"); // Button pressed twice without reset.
}
else{
rowSelected = i;
columnSelected =j;
// If odd * odd board and selected postion is odd then No path is possible.
if(row%2 ==1 && column%2 == 1 && rowSelected%2 ==0 && columnSelected%2 == 1 || row%2 ==1 && column%2 == 1 && rowSelected%2 ==1 && columnSelected%2 == 0){
lblPath.setText(" Path not possible from this point");
}
else{
int count;
lblStartRow.setText("Starting Row : "+String.valueOf(rowSelected + 1));
lblStartColumn.setText("Starting Column : "+String.valueOf(columnSelected + 1));
count = 1;
flag = 1;
startTour(); //Start tour function called.
for(int q=0;q<row;q++){
for(int w=0;w<column;w++){
if(array[i][j] == 0){
count++;
}
}
}
if(count > 2){
lblPath.setText(" No Path found");
}
//Printing path of the knight here.
else{
for(int k=0;k<pathArray.length;k++){
path = path+"->"+ pathArray[k];
}
lblPath.setText(" Path : \n"+ path.substring(5));
}
btnPressed = 1;
break;
}
}
}
}
}
} }
//Function for the animation.
void animate(){
if(btnPressed == 1){
btnPressed =0;
Graphics g = getGraphics();
for(int i=0;i<(row*column)-1;i++){
try {
Thread.sleep(600); // this function slows down drawing of lines.
} catch (InterruptedException ex) {
}
g.setColor(Color.RED); // setting colour or line to red.
g.drawLine((coordinatesArray[i][0]+65),(coordinatesArray[i][1]+50),(coordinatesArray[i+1] [0]+65),(coordinatesArray[i+1][1]+50));
}
}
else{
lblPath.setText(" Please clear, select a button to see the animation again"); //Animate button pressed twice without clear.
}
}
//This function calls the neighbour function with the selected row and column by the user.
static void startTour(){
neighbourRecursion(rowSelected,columnSelected);
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
I have an implementation of this program in C#. You can find it here:
http://github.com/danieltian/KnightBoard
It will only find the first solution though. I'm not saying to copy it, but you can take a look at it and see if it helps.