I am creating a java GUI which is a fortune teller. The GUI will spit out one of twelve fortunes every time you click the "get my fortune" button, the strings will never repeat back to back, can can repeat later after other strings have gone before it. I have made already for the most part. But now I am having some trouble creating the while loops to display the strings without repeating. I have looked at my book which didn't really help. If you guys could point me in the right direction,it would be much appreciated. Thanks!
I entered all of the code so you can see the variables used. But my question starts at class RndButtonListener.
package FortuneTellerRunner;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
* #author a3cal_000
*/
class FortuneTellerFrame extends JFrame
{
final private JPanel mainPnl, titlePnl, displayPnl, buttonPnl, imagePnl;
final private JButton quitBtn, rndBtn;
final private JLabel titleLbl, iconLbl;
final private JTextArea displayTa;
final private JScrollPane scroller;
public String[] fortune = new String [12];
int newIndex, oldIndex;
private static final int HEIGHT = 250;
private static final int WIDTH = 450;
public FortuneTellerFrame()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPnl = new JPanel();
mainPnl.setLayout(new BorderLayout());
displayPnl = new JPanel();
buttonPnl = new JPanel();
titlePnl = new JPanel();
ImageIcon icon = new ImageIcon("FortuneTellerIcon.JPEG");
iconLbl = new JLabel(icon);
titleLbl = new JLabel("Fortune Teller!");
displayTa = new JTextArea();
imagePnl = new JPanel();
scroller = new JScrollPane();
// Create the layout of the title panel
titlePnl.setLayout(new GridLayout(2,1));
add(mainPnl);
// Set the label to the panel.
titlePnl.add(titleLbl);
titlePnl.add(iconLbl);
// add the panel to the main panel.
mainPnl.add(titlePnl, BorderLayout.NORTH);
mainPnl.add(scroller, BorderLayout.CENTER);
mainPnl.add(displayTa, BorderLayout.CENTER);
// Create the "Get my fortune button.
rndBtn = new JButton("Get My Fortune!");
quitBtn = new JButton("Quit");
// Add the buttons to the buttonPnl in grid layout.
buttonPnl.add(rndBtn);
buttonPnl.add(quitBtn);
// Create the grid layout for the button panel.
buttonPnl.setLayout( new GridLayout(1, 2));
// Add the button panel to the grid layout, South.
mainPnl.add(buttonPnl, BorderLayout.SOUTH);
ActionListener listener = new RndButtonListener();
rndBtn.addActionListener(listener);
quitBtn.addActionListener(listener);
}
class RndButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
fortune[0] = "He who throws dirt is losing ground.";
fortune[1] = "You will find the love of your life in food.";
fortune[2] = "Do or do not, there is no try.";
fortune[3] = "Tomorrow is a better day to try anything of importance.";
fortune[4] = "Life's not about how hard you can hit, but how hard you can get hit and keep moving forward.";
fortune[5] = "You can't be late until you show up.";
fortune[6] = "If you think things can't get worse it's probably only because you lack sufficent imagination.";
fortune[7] = "If youre at the top it means you have further to fall.";
fortune[8] = "Even in last place, youre still in the race.";
fortune[9] = "The road to riches is paved on the failures of others.";
fortune[10] = "If you feel like your going no where, get off the treadmill.";
fortune[11] = "Thinking about going to the gym is just as good as going.";
Random rnd = new Random(fortune.length);
do
{
newIndex = rnd.nextInt(fortune.length);
}
while(newIndex == oldIndex);
do
{
System.out.println(fortune[newIndex]);
displayTa.append(fortune[newIndex] + "||");
displayTa.updateUI();
mainPnl.updateUI();
oldIndex = newIndex;
}
while(newIndex != oldIndex);
class QuitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
}
}
}
}
The basic problem is you are re-creating the Random with the same seed each time, which is generally creating the same random sequence over and over again.
Instead try using...
do {
newIndex = (int) Math.round(Math.random() * (fortune.length - 1));
} while (newIndex == oldIndex);
You also don't need the second loop, it's just clutter that confuses the situation.
You may also find that...
displayTa.append(fortune[newIndex] + "\n");
produces nicer output (IMHO)
You may also wish to take a look at How to use Scroll Panes
Your program run fine, but this is a problem, fortune.length is a random seed which return me only 6 and 8 when I later called Random.nextInt().
Random rnd = new Random(fortune.length);
Do it this way
Random rnd = new Random();
and also consider the formatting solution given by MadProgrammer.
Random() gives you same number pattern. Try Random(System.currentTimeMillis()). It uses current time as seed, so you can get real random numbers.
I did something similar to this just today, so let's see if I can remember... I made an ArrayList of type int of how many items I had (fortunes)
ArrayList<Integer> fortuneSeq = new ArrayList<Integer>();
Then add in some numbers starting from 0 to code for the fortunes.
for(int i = 0; i < fortune.length; i++) {
fortuneSeq.add(i);
}
Then I used the shuffle() method from the Collections class to randomize the list.
Collections.shuffle(fortuneSeq);
After that, just loop through to access the fortunes.
for(int i = 0; i < fortune.length; i++) {
System.out.println(fortune[fortuneSeq.get(i)]);
//...
}
Edit: Silly autocorrect, you don't like programmers.
Edit: Fixed some furtunes instead of fortunes and fixed println statement.
Related
I wanted to create JButton to change color every time it is clicked but it doesn't change after second click.
It is strange because with Random().nextInt(250) instead of i it works.
What could be the problem?
Here's the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout(100, 100));
JButton l = new JButton("Hello");
l.setBackground(new Color(245, 12, 53));
jp.add(l, BorderLayout.EAST);
jf.add(jp);
jf.setSize(200, 200);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
l.addActionListener(new ActionListener() {
Integer i = new Integer(0);
Color c = new Color(150, 10, i);
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (i < 200) {
i += 50;
c = new Color(150, 10, i);
l.setBackground(c);
} else
i = 0;
}
});
}
}
I debugged your code and saw that the value of c change, every time I click the button. The first value is (r=150,g=10,b=50), then turns into (r=150,g=10,b=100), then (r=150,g=10,b=150) etc.
This means that the color is indeed changing. It's just that the difference is too small for you to notice.
So why does random.nextInt work?
With a random value in the blue component. The value can jump very suddenly from 0 to 200. The color difference is so large that your eyes can see it. But with a gradual change of 50 every time, you only notice it the first time.
Just test it with new Color(0, 0, i). I think that will make a bigger difference. It will go from black to blue!
Works fine for me.
Although the code should probably be something like:
if (i < 200)
i += 50;
else
i = 0;
c = new Color(150, 10, i);
l.setBackground(c);
Otherwise there will be one click that doesn't change the color.
You may want to consider using HSL Color this will allow you to change the Color in a more meaningful way by either changing the hue of the Color or shade/tone of the Color.
I'm working on a project for work and I have reached an unusual problem. I have a JTable that the user can populate with data. In my actual code there is an "add row" button that lets the user fill out some GUI's and that information generates the row.
Another important feature of this is a button to clone rows. Since the process of adding a row can be very time consuming (there are many fields to fill out) if a user only needs to add a new row with 1 cell different then he can clone the cell using the button.
This clone button works as expected however there is a rather odd problem. Once a row has been cloned I noticed that when I attempt to change the contents of any cells that have been cloned there are unexpected results. For example if I change a cell's contents to "Ryan" then other cells may also suddenly change and if I even click on a cell after changing one the cell I click on will change by itself. I'm quite sure that this problem is related to the clone method I just really have no idea to fix.
I created a verifiable program so you can text it out for yourself and see what I'm talking about. Just use the clone button a few times and then try changing the contents of individual cells and watch the results in the other cells..
I really need to fix this but I'm lost on what to do, and help is GREATLY appreciated.
Main Class
package jtabletest;
public class JTableTestMain
{
public static void main(String args[]){
JTableTest jTest = new JTableTest();
jTest.createGUI();
}
}
JTable Class
package jtabletest;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class JTableTest
{
protected static DefaultTableModel dtm = new DefaultTableModel();
public static JTable tbl;
public void createGUI(){
final JFrame frame = new JFrame("JTable Test");
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel panelNorth = new JPanel(new BorderLayout());
JPanel panelSouth = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel();
JButton cloneButton = new JButton("Clone");
cloneButton.setPreferredSize(new Dimension(150,40));
buttonPanel.add(cloneButton);
JButton printButton = new JButton("Print");
printButton.setPreferredSize(new Dimension(150,40));
buttonPanel.add(printButton);
tbl = new JTable();
String header[] = new String[]{
"Employee", "Pay-Rate", "Hours Worked"};
dtm.setColumnIdentifiers(header);
tbl.setModel(dtm);
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for(int i = 0; i < header.length; i++){
tbl.getColumnModel().getColumn(i).setPreferredWidth(200);
}
dtm.addRow(new Object[]{"Pete","$10.00","40"});
dtm.addRow(new Object[]{"Bob","12.50","42"});
dtm.addRow(new Object[]{"Jamar","$7.25,25"});
cloneButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
int[] selectedRows = tbl.getSelectedRows();
if(selectedRows.length>0){
#SuppressWarnings("rawtypes")
Vector data = dtm.getDataVector();
int insertPoint = selectedRows[selectedRows.length-1]+1;
for(int i = 0; i < selectedRows.length; i++){
#SuppressWarnings("rawtypes")
Vector targetRow = (Vector)data.elementAt(selectedRows[i]);
dtm.insertRow(insertPoint, targetRow);
insertPoint++;
}
dtm.fireTableDataChanged();
}
}
});
printButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(null != tbl.getCellEditor()){
tbl.getCellEditor().stopCellEditing();
}
for(int i = 0; i < tbl.getRowCount(); i++){
System.out.println(tbl.getValueAt(i, 0));
System.out.println(tbl.getValueAt(i, 1));
System.out.println(tbl.getValueAt(i, 2));
}
}
});
panelNorth.add(tbl,BorderLayout.NORTH);
panelNorth.setPreferredSize(new Dimension(500,500));
panelSouth.add(buttonPanel,BorderLayout.NORTH);
mainPanel.add(panelNorth,BorderLayout.NORTH);
mainPanel.add(panelSouth,BorderLayout.SOUTH);
frame.add(mainPanel);
frame.setVisible(true);
frame.setSize(1900,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
It sounds like you are reusing the same reference rather than copying new objects on the clone method. I would suggest doing the following.
1) First create a new Vector and see if that will do the trick, like so.
for(int i = 0; i < selectedRows.length; i++){
#SuppressWarnings("rawtypes")
Vector targetRow = (Vector)data.elementAt(selectedRows[i]);
Vector newVector = new Vector();
for (int t = 0; t < targetRow.size(); t++) {
newVector.add(targetRow.get(t));
}
dtm.insertRow(insertPoint, newVector);
insertPoint++;
}
and see if this will resolve your problem. If it does you are done. If it doesn't then
2) Create a new Vector similar to above, for any Class based object in the Vector recreate them as currently you are dealing with pointers.
It's a bit hard for me to say if #1 will fix your problem as I don't know the contents of the Vector coming from the table, if it is primitives you are probably safe otherwise you may need to do solution #2.
Your problem is in this line:
Vector targetRow = (Vector)data.elementAt(selectedRows[i]);
you are not creating a copy, you are creating a new reference so when you add
dtm.insertRow(insertPoint, targetRow)
the row you are adding is actually the same, not a copy of the previosly selected row.
You will have to use something like
Vector aux = (Vector)data.elementAt(selectedRows[i]);
Vector targetRow = aux.clone();
to make it work.
Clone is the keyword here. You are not cloning the data. You are just copying the references from one Vector to another. So since each row shares the same references the value appears in both rows.
So you need to actually clone each element.
The code would be something like:
Vector targetRow = (Vector)data.elementAt(selectedRows[i]);
Vector clonedRow = new Vector(targetRow.size());
for (Object object: targetRow)
{
clonedRow.addElement( object.clone() );
}
Note, I've never used clone() before so you might be able to use:
Vector targetRow = (Vector)data.elementAt(selectedRows[i]);
Vector clonedRow = targetRow.clone();
but I'm not sure if it just clones the Vector and not the elements in the Vector.
Also, you would never invoke the firstTableDataChanged() method. That is the job of the DefaultTableModle to fire the appropriate method when the insertRow(...) method is invoked.
Edit:
Yes, using the clone does work but you need to clone the Vector not each item in the Vector:
//dtm.insertRow(insertPoint, targetRow);
dtm.insertRow(insertPoint, (Vector)targetRow.clone());
or
dtm.insertRow(insertPoint, new Vector(targetRow));
I was learning about arrays today in school, and I am trying to do this problem, but cannot figure it
// Fortune Teller
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class FortuneTeller extends JFrame
implements ActionListener
{
private static final EasySound ding = new EasySound("ding.wav");
// Declare an array of "fortunes" (strings):
___________________________________________
...
private JTextField display;
public FortuneTeller()
{
super("Fortune Teller");
display = new JTextField(" Press \"Next\" to see your fortune...", 25);
display.setBackground(Color.WHITE);
display.setEditable(false);
JButton go = new JButton("Next");
go.addActionListener(this);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(display);
c.add(go);
}
public void actionPerformed(ActionEvent e)
{
// Pick and display a random fortune:
___________________________________________
...
display.setText(" " + __________________ );
ding.play();
}
public static void main(String[] args)
{
JFrame window = new FortuneTeller();
window.setBounds(300, 300, 300, 100);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
}
I am trying to fill in the blanks.
For the first one,, would it just be just be String [] Fortune;?
But how would I end up initializing it?
And then for the second part, what would I have to do?
Please help as I am extremely lost.
Here are some hints to help you (without actually doing your homework for you).
You can create and populate an array of strings in one line using the following syntax:
String[] colours = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};
You can generate a random number between zero and x (inclusive) using the following syntax:
int randomNumber = Math.random() * (x + 1);
You can select a random string from an array with the following syntax:
String randomColour = colours[Math.random() * colours.length];
As found by the simple Google search "How to declare an array in Java":
String[] fortune = {"You're going to be right","You're going to die","You're going to find a cat"};
This also initializes the array.
Then to get the an element of the array, you do:
fortune[1];
//Returns: You're going to die
For this though, I'd do a random number generator to pick a number between 0 and the length of the array:
int value = Math.random() * fortune.length;
fortune[value];
For this program, the JButton doesn't seem to show up unless you click the area where the JButton should be; the JFrame starts up blank. The moment you click the button, the respective code runs and the button finally shows up.
How do I get the buttons to show up upon starting the program?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/*
The Amazing BlackJack Advisory Tool by JoshK,HieuV, and AlvinC.
Prepare to be amazed :O
*/
public class BlckJackUI {
//main class, will contain the JFrame of the program, as well as all the buttons.
public static void main(String args[])
{
//Creating the JFrame
JFrame GUI = new JFrame("Blackjack Advisor");
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(1300, 900);
GUI.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Hieu Vo\\Desktop\\Green Background.png")));
GUI.setVisible(true);
// Because each button needs to run through the Math class.
final Math math = new Math();
// The Ace Button:
ImageIcon Ace = new ImageIcon("/Users/computerscience2/Downloads/Ace.jpg");
JButton ace = new JButton(Ace);
ace.setSize(300, 100);
ace.setLocation(100, 100);
ace.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Automatically default the the Ace to 11, and if Bust, Ace becomes 1.
if (math.array.playerhandtotal <= 21)
{
math.cardvalue = math.cardvalue + 11;
}
else
{
math.cardvalue = math.cardvalue + 1;
}
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
GUI.add(ace);
ImageIcon Two = new ImageIcon("/Users/computerscience2/Downloads/2.jpg");
JButton two = new JButton(Two);
two.setSize(300, 100);
two.setLocation(100, 200);
two.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
/*
This generally repeats throughout the whole class, and the only
thing different is the changing cardvalue. When a button is pressed,
respective cardvalues are added into the playerhand ArrayList, and
totaled up to form playerhandtotal, which is a major factor in
bringing up the advice.
*/
math.cardvalue = math.cardvalue + 2;
math.array.clicktracker++;
math.calcResult();
JOptionPane.showMessageDialog(null,math.array.result);
}
});
GUI.add(two);
Et cetera, Et cetera... Just a bunch of the same stuff, more buttons coded the same exact way as JButton two, but with different value associated to them.
JButton start = new JButton("Start/Reset");
start.setSize(300, 100);
start.setLocation(500,500);
start.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
/*
The start button also acts like a reset button, and the concept is fairly
simple. If we reset all the important values to 0 or "null," then the
program acts as if it was just opened.
*/
Arrays array = new Arrays();
array.playerhand.clear();
array.dealer = 0;
math.array.starttracker++;
math.array.clicktracker = 0;
array.playerhandtotal = 0;
math.cardvalue = 0;
array.result = null;
JOptionPane.showMessageDialog(null,"Please select the card \nthat the dealer is showing :)");
}
});
GUI.add(start);
GUI.setLayout(null);
This is all in the same class, and I understand a layout would be nicer, but perhaps there's a way to fix this issue using what I have now?
The program starts blank because you are calling setVisible before you add components. Call setVisible after you add components (in the end of contructor) and it should work fine.
Also, avoid absolute positioning and call of set|Preferred|Minimum|MaximumSize methods for your components. Learn how to use layout managers.
Write GUI.validate(); after you add all the components to your frame. Any time you add something to a frame you have to validate it like this. Otherwise, you will get the behavior that you have described.
No. The problem is caused by the layout. Before adding anything to a JFrame or a JPanel which you want it to have an absolute position, you have to setLayout(null). Otherwise, you'll have unexpected behaviours all the time. I just figured it out by myself after three hours of experimenting; suddenly, I connected your post with other different subject, and it worked, but this isn't well explained on the Internet yet.
I am working on a java game for class where we implement a game of nim. I thought that I was nearing completion but when I ran the program, nothing appears. It just says build successful and quits. I never get to see the game or play it. Below is my code for the application.
package Nim;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Nim extends JFrame implements ActionListener {
// Number of stickSpace that is needed for the sticks;
int rowspace = 3;
// Buttons for the human to click to take turns playing witht the computer.
private JButton humanMove,
computerMove;
// whatRow = what row the user would like to remove from
// howMany = how many sticks to take from each row
private JComboBox whatRow,
howMany;
// Creates an array of JTextFields with the rowspace as a size.
private JTextField[] stickSpace = new JTextField[rowspace];
// Creates the game;
private Nimgame nimgame;
public void Nim(){
//As requireed, we use a loop to fill the array.
for(int i=0; i<rowspace ;i++){
stickSpace[i] = new JTextField(5);
}
// Creates pulldown menus for the user to select the whatRow s/he
// wants to choose from, and another for howMany s/he wants to take.
whatRow = new JComboBox();
howMany = new JComboBox();
// Add the options to the pulldown menus so the player can choose.
// 0-2 because the array index starts at 0. 1-3 for the amount of sticks.
for(int p=0; p<=3; p++){
if(p<3){
whatRow.addItem(p);
}
if(p>0){
howMany.addItem(p);
}
}
// Adds the text "Human Turn" and "CPU Turn" to the buttons used for turns.
humanMove = new JButton("Human Turn");
computerMove = new JButton("CPU Turn");
// Adds a listener to the buttons to signal the game its time to act.
humanMove.addActionListener(this);
computerMove.addActionListener(this);
// Creates a gridlayout (3,2) with 3 rows and two columns.
JPanel gridpanel = new JPanel(new GridLayout(3,2));
// Labels the rows so the player knows it starts at row Zero - Three.
gridpanel.add(new JLabel("Row Zero", JLabel.LEFT));
gridpanel.add(stickSpace[0]);
gridpanel.add(new JLabel("Row One", JLabel.LEFT));
gridpanel.add(stickSpace[1]);
gridpanel.add(new JLabel("Row Two", JLabel.LEFT));
gridpanel.add(stickSpace[2]);
// Creates another gridlayout this time with 4 rows and 2 columns.
// This sill be used to add the comboboxes, labels, and buttons.
JPanel mainPanel = new JPanel(new GridLayout(4,2));
mainPanel.add(new JLabel("Remove from Row:", JLabel.RIGHT));
mainPanel.add(whatRow);
mainPanel.add(new JLabel("# To Remove:", JLabel.RIGHT));
mainPanel.add(howMany);
mainPanel.add(humanMove);
mainPanel.add(computerMove);
// This adds the gridpanel and the main panel to the visual
// application, but they are still not visiable at this moment.
getContentPane().add(gridpanel, BorderLayout.NORTH);
getContentPane().add(mainPanel, BorderLayout.SOUTH);
// This sections sets the title, size, position on screen, sets it visiable,
// sets the background color, and makes it exit on close of the visual application.
setTitle("The Game of Nim");
setSize(300, 250);
setBackground(Color.yellow);
setVisible(true);
// Creates the actual game to play.
nimgame = new Nimgame();
// Prints out the sticks in each row.
for(int p=0; p<3; p++){
stickSpace[p].setText(nimgame.addSticks(p));
}
}
// Method to handle when an action lister find an action event
public void actionPerformed(ActionEvent e){
// Checks if the humanMove button has been pressed
if(e.getSource() == humanMove){
int foo = whatRow.getSelectedIndex();
int bar = howMany.getSelectedIndex()+1;
nimgame.stickRemove(foo, bar);
for(int p=0; p<3; p++){
stickSpace[p].setText(nimgame.addSticks(p));
}
}
// Checks if the computerMove button has been pressed.
if(e.getSource() == computerMove){
nimgame.computerRandom();
for(int p=0; p<3; p++){
stickSpace[p].setText(nimgame.addSticks(p));
}
}
// Checks to see if the game is over or not.
if(nimgame.isDone()){
JOptionPane.showMessageDialog(null, "Game Over Player Player" + nimgame.whoWon());
}
}
public static void main(String[] args) {
Nim NIM = new Nim();
}
}
Any idea why nothing would be showing up? I figured I forgot to setVisible, but that wasn't the case. Any help would be much appreciated.
public void Nim(){
This isn't a constructor, it's a void method declaration with an awfully confusing name. As you don't declare a constructor at all, you have an implicit default constructor which is called here:
Nim NIM = new Nim();
but the default constructor doesn't do what you'd expect, so you don't see anything. To fix this, change the aforementioned method definition to a constructor definition by removing void:
public Nim() {