Ok, i have been working on a simplistic game for about an hour now. This is what i have so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Game extends JApplet
{
private int APPLET_WIDTH = 500, APPLET_HEIGHT= 100;
private int money;
private int owned;
private JLabel labelMoney;
private JLabel labelOwned;
private JButton Buy;
private JButton Sell;
private int cost = 100;
private int sellPrice = 50;
public void init ()
{
money = 500;
owned = 1;
Buy = new JButton ("Buy");
Buy.addActionListener (new BuyButtonListener());
Sell = new JButton ("Sell");
Sell.addActionListener (new SellButtonListener());
labelMoney = new JLabel ("Money: " + Integer.toString (money));
labelOwned = new JLabel ("Owned: " + Integer.toString (owned));
Container cp = getContentPane();
cp.setBackground (Color.lightGray);
cp.setLayout (new FlowLayout());
cp.add (Buy);
cp.add (Sell);
cp.add (labelMoney);
cp.add (labelOwned);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
private class BuyButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
money -= cost;
++owned;
labelMoney.setText ("Money: " + Integer.toString (money));
labelOwned.setText ("Owned: " + Integer.toString (owned));
if(money >= cost)
{
Buy.setEnabled (true);
}
repaint ();
if(money < cost)
{
Buy.setEnabled (false);
}
repaint ();
}
}
private class SellButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
money += sellPrice;
--owned;
labelMoney.setText ("Money: " + Integer.toString (money));
labelOwned.setText ("Owned: " + Integer.toString (owned));
if(owned >= 0)
{
Sell.setEnabled (true);
}
repaint ();
if(owned <= 0)
{
Sell.setEnabled (false);
}
repaint ();
}
}
}
Basically, as you buy and sell these objects i want the buy and sell buttons disabling and enabling depending on whether you have any objects or not. at this point the buttons will disable, but never re-enable themselves.
I have tried If else for the if statements i have in, but they did not work either. So i tried separate if statements with a repaint (); between them, but no luck.