public class CoolPool
{
public CoolPool()
{
}
public static void main(String[ ] args )
{
Start start = new Start();
//Table table = new Table();
}
}
public class Start implements ActionListener
{
private static JFrame startF = new JFrame();
private static JPanel startP = new JPanel();
private static JButton start = new JButton("Start");
private static JButton exit = new JButton("Exit");
/*To create a window that then can be show on the screen.*/
public Start()
{
startF.setContentPane(startP);
startP.setLayout(null);
start.setBounds(270,292,200,25);
startP.add(exit);
exit.setBounds(270,338,200,25);
startP.add(start);
start.addActionListener(this);
exit.addActionListener(this);
startF.setTitle("CoolPool");
startF.setSize(750, 750);
startF.setLocation(400, 100);
startF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
startF.setVisible(true);
}
/*Design click button*/
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
startF.setVisible(false);
startF.dispose();
PlayerChoose pc = new PlayerChoose();
}
else if(e.getSource() == exit)
{
startF.setVisible(false);
startF.dispose();
}
}
public JButton getStart()
{
return start;
}
public JButton getExit()
{
return exit;
}
}
public class PlayerChoose implements ActionListener
{
private static JFrame cF = new JFrame();
private static JPanel cP = new JPanel();
private static JTextArea textarea = new JTextArea("There will be two players participating in this game, ");
private static JTextArea textarea2 = new JTextArea("so we will randomly choose who comes first.");
private static JTextArea textarea3 = new JTextArea(" When you click the OK button, if the number shows 1,");
private static JTextArea textarea4 = new JTextArea(" Player1 (the clicker) first, and if it is 2, Player2 first. ");
private static JButton OK = new JButton("OK");
/*To create a window that then can be show on the screen.*/
public PlayerChoose()
{
cF.setContentPane(cP);
cP.setLayout(new FlowLayout());
//OK.setBounds(300,342,200,25);
cP.add(textarea);
cP.add(textarea2);
cP.add(textarea3);
cP.add(textarea4);
cP.add(OK);
OK.addActionListener(this);
cF.setTitle("CoolPool");
cF.setSize(750, 150);
cF.setLocation(400, 300);
cF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cF.setVisible(true);
}
/*Design click button*/
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == OK)
{
cF.setVisible(false);
cF.dispose();
Coin coin = new Coin();
Table table = new Table();
}
}
public JButton getOK()
{
return OK;
}
}
public class Coin implements ActionListener
{
private static JFrame rF = new JFrame();
private static JPanel rP = new JPanel();
private static JButton close = new JButton("Close");
private static int coin;
private static JTextArea ta1 = new JTextArea(" The number is ");
private static JTextArea ta2 = new JTextArea(" 1 ");
private static JTextArea ta4 = new JTextArea(" 2 ");
private static JTextArea ta3 = new JTextArea(" Player 1 first ");
private static JTextArea ta5 = new JTextArea(" Player 2 first ");
public Coin()
{
setCoin();
rF.setContentPane(rP);
rP.setLayout(new FlowLayout());
rP.add(ta1);
if(coin == 1)
{
rP.add(ta2);
rP.add(ta3);
}
else if(coin == 2)
{
rP.add(ta4);
rP.add(ta5);
}
rP.add(close);
close.addActionListener(this);
rF.setTitle("CoolPool");
rF.setSize(200, 200);
rF.setLocation(50, 300);
rF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rF.setVisible(true);
}
public static int setCoin()
{
Random r = new Random();
int num = r.nextInt(2);
num = num + 1;
coin = num;
return coin;
}
/*Design click button*/
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == close)
{
rF.setVisible(false);
rF.dispose();
}
}
}
public class Table
{
private static GameArena ga = new GameArena(886,528);
private static Text words = new Text("Welcome to CoolPool v1.0",14,29,15,"WHITE",1);
private static Text player1 = new Text("Player 1:",10,29,456,"WHITE",1);
private static Text player2 = new Text("Player 2:",10,29,476,"RED",1);
private static Rectangle g = new Rectangle(58,57,712,356,"GREEN",1);
private static Rectangle l = new Rectangle(205,57,1,356,"WHITE",1);
private static Ball b[] = {new Ball(58,57,44,"BLACK",2),new Ball(58,413,44,"BLACK",2),new Ball(770,57,44,"BLACK",2),new Ball(770,413,44,"BLACK",2),
new Ball(414,57,44,"BLACK",2),new Ball(414,413,44,"BLACK",2),new Ball(205,235,4,"WHITE",2)};
private static Rectangle r = new Rectangle(29,29,29,412,"GREY",4);
private static Rectangle r1 = new Rectangle(29,29,770,28,"GREY",4);
private static Rectangle r2 = new Rectangle(29,413,770,28,"GREY",4);
private static Rectangle r3 = new Rectangle(770,29,29,412,"GREY",4);
private static Iballs ib = new Iballs(ga);
private static Line wl;
private static boolean exist = false;
private static boolean clicked = false;
private static Rectangle rr;
public Table()
{
ga.addText(words);
ga.addText(player1);
ga.addText(player2);
ga.addRectangle(g);
ga.addRectangle(l);
ga.addBall(b[0]);
ga.addBall(b[1]);
ga.addBall(b[2]);
ga.addBall(b[3]);
ga.addBall(b[4]);
ga.addBall(b[5]);
ga.addBall(b[6]);
ga.addRectangle(r);
ga.addRectangle(r1);
ga.addRectangle(r2);
ga.addRectangle(r3);
game_Go();
}
public static void drawLine()
{
wl = new Line(ib.getWx(),ib.getWy(),ga.getMousePositionX(),ga.getMousePositionY(),1,"WHITE",4);
ga.addLine(wl);
}
public static void drawRedrectangle()
{
double rLength = wl.getLength() * 2;
if (rLength >= 412)
{
rLength = 412;
}
rr = new Rectangle(828, 29, 29, rLength, "RED", 4);
ga.addRectangle(rr);
}
public static void game_Go()
{
while(true)
{
if (ga.leftMousePressed() == true)
{
if (ib.ckWhite() == true)
{
exist = true;
clicked = true;
}
else if (clicked == true)
{
cSpeed();
clicked = false;
exist = false;
}
}
if (exist == true)
{
drawLine();
drawRedrectangle();
}
ga.pause();
ib.changePosition();
ga.removeLine(wl);
ga.removeRectangle(rr);
}
}
public static void cSpeed()
{
ib.wbSpeed((wl.getXStart() - wl.getXEnd())/7, (wl.getYStart() - wl.getYEnd())/7);
}
public GameArena getGa()
{
return ga;
}
}
When I click the start button in the Start window, it will jump to the PlayerChoose window. Then I click the OK button. At this time, the table window and the Coin window should pop up at the same time, but the problem now is that the two windows that pop up are blank. I have checked that if you don't open the table window and only open the Coin window, the Coin window that pops up will be normal. And if the table window is placed in the main of CoolPool, it is normal. Therefore, I want to know why the two windows opened at this time are blank.enter image description here
enter image description here
enter image description here
Related
I am trying to write a GUI temperature converter. It has one JTextField and two JButtons. TextField accepts the temperature which the user wants to convert and the user presses the appropriate button. Whenever I click on anyone of the buttons, I get a "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String" error. Please Help!
public class tempcon extends JFrame {
private JPanel panel;
private JLabel messageLabel;
public JTextField tempC;
private JButton calcButton, calcButton1;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 140;
public tempcon() {
setTitle("Temperature convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
public double getTempC(){
return Double.parseDouble(tempC.getText());
}
private void buildPanel() {
tempC = new JTextField(10);
messageLabel = new JLabel("Enter tempurture");
calcButton = new JButton("Convert to Fahrenheit");
calcButton1 = new JButton("Convert to Celcius");
calcButton.addActionListener(new CalcButtonListener());
calcButton1.addActionListener(new CalcButtonListener1());
panel = new JPanel();
panel.add(messageLabel);
panel.add(tempC);
panel.add(calcButton);
panel.add(calcButton1);
}
public static void main(String[] args){
new tempcon().buildPanel();
}
}
class CalcButtonListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = input * 1.8 + 32;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Celsius.");
}
}
class CalcButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = (input - 32)*1.8;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Fehrenheit.");
}
public static void main(String[] args) {
tempcon myTempWindowInstance = new tempcon();
}
}
The problem is that you are recreating a new frame in your action listeners : new tempcon().getTempC() .
The textfields in these new frames are obviously empty and you get your error.
Consider referring to the same instance of tempcon everywhere, that is simply replace
new tempcon().getTempC();
with
getTempC();
, which will call the getTempC() method of the outer tempcon instance .
I'd like to start off by saying that I'm relatively new to working with swing in Java. I can make swing do things, like in gaming, but I'm not sure if I truly understand what's going on behind the scenes. So, I started working on a game, kind of like Civilization, in Java and I've made some decent progress. I wanted to turn my attention to saving the game and loading it back up. However, I've run into a bit of trouble with this. So I did some research and I found out about making an object serializable and saving/loading from there. That worked great, I can save my game and load it up. The issue is, everything appears on the screen again (Terrain tiles, units, HUD) but it seems that the data that was stored in some of my objects has been set back to its initialization point. For example, I can end on tile 41 in the X direction, but when I load the game it sets it back to 0.
A brief description of how I set the game up: I have a Main class that creates a new Window object. The Window object is essentially a JFrame that contains button information and a Panel class that is just the JPanel that the game gets painted in. Everything that happens in the game gets created in the JPanel. I'm not new to programming, I'm a computational Materials Scientist, but I'm new to writing games in Java, and I feel like I'm making a really simple mistake. I'll post the JFrame and JPanel (part of it, it's quite long) below.
Frame
public class GameWindow extends JFrame implements ActionListener
{
//ints
private int fCounter = 0;
//timers
private Timer t;
//Panels
private GamePanel gamePanel;
//menu bars
private JMenuBar menuBar;
//menus
private JMenu fileMenu;
//menu items
private JMenuItem save;
private JMenuItem load;
private JMenuItem exit;
private JMenuItem newGame;
//menu panels
private JPanel menuPanel;
//File objects
private File file;
//File Chooser
private JFileChooser chooser;
//user objects
private Player humanPlayer;
private AI aIPlayer;
private FileActions fileActions;
//**************************************************************************constructor
public GameWindow()
{
//set specifications for frame
super("New Game v 0.00: pre-Alpha");
this.setResizable(false);
setFocusable(true);
setSize(1600, 800);
//creates a new menubar
menuBar = new JMenuBar();
//craetes a new file menu
fileMenu = new JMenu("File");
//creates the file options
save = new JMenuItem("Save");
save.addActionListener(this);
load = new JMenuItem("Load");
load.addActionListener(this);
newGame = new JMenuItem("New Game");
newGame.addActionListener(this);
exit = new JMenuItem("Exit");
exit.addActionListener(this);
//adds file options to the file menu
fileMenu.add(save);
fileMenu.add(load);
fileMenu.add(newGame);
fileMenu.add(exit);
//adds the file menu to the menubar
menuBar.add(fileMenu);
//establishes the menu panel as a new JPanel
menuPanel = new JPanel();
//adds the menu to the menubar
menuPanel.add(menuBar);
//sets user class objects
humanPlayer = new Player();
aIPlayer = new AI();
fileActions = new FileActions();
//panels
gamePanel = new GamePanel();
gamePanel.setSize(750, 750);
gamePanel.setFocusable(true);
addKeyListener(gamePanel);
addMouseListener(gamePanel);
addMouseMotionListener(gamePanel);
setVisible(true);
//adds panels to the frame with layout
add(menuPanel, BorderLayout.EAST);
add(gamePanel, BorderLayout.CENTER);
//add file choosers
chooser = new JFileChooser();
//adds file objects
file = new File("");
//timers
t = new Timer(1, this);
t.start();
}
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
//save a game
if(e.getSource() == save)
{
//fCounter = chooser.showSaveDialog(this);
//if(fCounter == JFileChooser.APPROVE_OPTION)
//{
//file = chooser.getSelectedFile();
fileActions.addObject(gamePanel);
fileActions.saveGame();
//}
}
//load a save file
if(e.getSource() == load)
{
this.remove(gamePanel);
gamePanel = fileActions.loadGame();
this.add(gamePanel);
gamePanel.setFocusable(true);
addKeyListener(gamePanel);
addMouseListener(gamePanel);
addMouseMotionListener(gamePanel);
add(gamePanel, BorderLayout.CENTER);
setVisible(true);
}
//starts a new game
if(e.getSource() == newGame)
{
//gamePanel = null;
//gamePanel = new GamePanel();
gamePanel.setNewGameSetup(true);
gamePanel.setMainMenuView(false);
}
//exits the game
if(e.getSource() == exit)
{
System.exit(0);
}
gamePanel.repaint();
}
}
Part of the Panel Class
public class GamePanel extends JPanel implements
ActionListener,KeyListener,MouseListener,MouseMotionListener,Serializable
{
//globals
private static int mapHeight = 0;
private static int mapWidth= 0;
private static int currentMapHoriztonal= 0;
private static int currentMapVertical= 0;
private static int currentMouseMapHoriztonal= 0;
private static int currentMouseMapVertical= 0;
private static int turnNumber= 0;
private int unitFocusNumber = -1;
private int cityFocusNumber = -1;
private Terrain[][] terrain;
private ArrayList<Unit> playerUnits = new ArrayList<Unit>();
private ArrayList<City> playerCities = new ArrayList<City>();
private boolean terrainCreate = true;
private boolean mainMenu = true;
private boolean newGameSetup = false;
private boolean mapView = false;
private boolean mapSizeOptions = false;
private boolean playerTurn = true;
private boolean[] move = new boolean[4];
private Font mainMenuTitle = new Font("Algerian",Font.BOLD,75);
private Font mainMenuOptions = new Font("Calibri",Font.BOLD,15);
private Player player = new Player();
private FileActions fA;
private AI aI = new AI();
public GamePanel()
{
}
//getters
public int getMapHeight()
{
return mapHeight;
}
public boolean getMapView()
{
return mapView;
}
public Terrain[][] getTerrain()
{
return terrain;
}
//setters
public void setMapHeight(int height)
{
mapHeight = height;
}
public void setMapWidth(int width)
{
mapWidth = width;
}
public void setMapView(boolean b)
{
mapView = b;
}
public void setMainMenuView(boolean b)
{
mainMenu = b;
}
public void setNewGameSetup(boolean b)
{
newGameSetup = b;
}
//painters
//paints the game
public void paintComponent(Graphics g)
{
if(mainMenu == true)
{
paintMainMenu(g);
}
if(newGameSetup == true)
{
paintSetupScreen(g);
}
else if(mapView == true)
{
if(terrainCreate == true)
{
//sets the terrain
terrain = new Terrain[mapHeight][mapWidth];
for(int i = 0; i < mapHeight; i++)
{
for(int j = 0; j < mapWidth; j++)
{
terrain[i][j] = new Terrain(j,i,mapWidth,mapHeight);
terrain[i][j].setTerrain(j,i);
}
}
for(int i = 0; i < 4; i++)
{
playerUnits.add(new Scout(75*i,75*i));
}
playerUnits.add(new Settler(75*9,75*8));
playerUnits.add(new Settler(75*14,75*12));
terrainCreate = false;
}
if(terrainCreate == false)
{
paintTerrain(g);
paintCities(g);
paintUnits(g);
paintHud(g);
}
}
}
Any help would be greatly appreciated!
Edit:
Here's the class that actually loads and saves the game.
public class FileActions implements Serializable
{
private ArrayList<Object> objects = new ArrayList<Object>();
//setters
public void addObject(Object o)
{
objects.add(o);
}
//getters
public void saveGame()
{
try
{ // Catch errors in I/O if necessary.
// Open a file to write to, named SavedObj.sav.
FileOutputStream saveFile=new FileOutputStream("NTT.sav");
// Create an ObjectOutputStream to put objects into save file.
ObjectOutputStream save = new ObjectOutputStream(saveFile);
// Now we do the save.
for(int i = 0; i < objects.size();i++)
{
save.writeObject(objects.get(i));
}
// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc)
{
exc.printStackTrace(); // If there was an error, print the info.
}
}
public GamePanel loadGame()
{
GamePanel stuff = new GamePanel();
try
{
// Open file to read from, named SavedObj.sav.
FileInputStream saveFile = new FileInputStream("NTT.sav");
// Create an ObjectInputStream to get objects from save file.
ObjectInputStream save = new ObjectInputStream(saveFile);
stuff = (GamePanel) save.readObject();
// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc)
{
exc.printStackTrace(); // If there was an error, print the info.
}
System.out.println(stuff);
return stuff;
}
}
Okay, so i did some more digging, essentially I shouldn't use static variables when using serialization as the method of saving because the static variables are not part of the GamePanel object but the class, so when the save method saves the object it doesn't actually save whatever the static variables had become. I made all variables that I need to save non-static and everything works great
Just need some help printing text to a TextArea for a class project. I have a method that generates 5 random numbers between 0-100 and want it to print to a TextArea but I am unsure on how to do that. (Right now I just have Syste.out.println as a placeholder but I would like to remove that)
public class Interface
{
public Interface()
{
}
public static void randomNumber()
{
Random randomNumber = new Random();
System.out.println("Generating 5 Random Numbers.");
for (int randomNum = 1; randomNum <= 5; ++randomNum)
{
int randomInt = randomNumber.nextInt(5);
System.out.println("Random Number: " + randomInt);
}
System.out.println("Done.");
}
}
public class InterfacePanel extends JPanel
{
private InterfaceController baseController;
private SpringLayout baseLayout;
private JButton buttonOne;
private JButton buttonTwo;
private JButton buttonThree;
private JButton buttonFour;
private JLabel lableOne;
private JLabel lableTwo;
private JLabel lableThree;
private JLabel lableFour;
private TextArea textField;
public InterfacePanel(InterfaceController baseController)
{
setBackground(Color.DARK_GRAY);
this.baseController = baseController;
buttonOne = new JButton("Random Numbers");
buttonTwo = new JButton("Two");
buttonThree = new JButton("Three");
buttonFour = new JButton("Four");
lableOne = new JLabel("5 Random Numbers");
lableTwo = new JLabel("Two");
lableThree = new JLabel("Three");
lableFour = new JLabel("Four");
baseLayout = new SpringLayout();
textField = new TextArea();
setupPanel();
setupLayout();
setupListeners();
}
private void setupPanel()
{
this.setLayout(baseLayout);
this.add(lableOne);
this.add(buttonOne);
this.add(buttonTwo);
this.add(buttonThree);
this.add(buttonFour);
this.add(lableTwo);
this.add(lableThree);
this.add(lableFour);
this.add(textField);
}
private void setupLayout()
private void setupListeners()
{
buttonOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
Interface.randomNumber();
}
});
buttonTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
buttonThree.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
buttonFour.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent click)
{
}
});
}
}
Add a parameter of JTextArea in randomNumber() method.
public static void randomNumber(JTextArea myText){
Random randomNumber = new Random();
System.out.println("Generating 5 Random Numbers.");
for (int randomNum = 1; randomNum <= 5; ++randomNum)
{
int randomInt = randomNumber.nextInt(5);
myText.setText(myText.getText() + randomInt + "\n");
}
System.out.println("Done.");
}
And call randomNumber() method in InterfacePanel class this way
Interface.randomNumber(textField);
I am having a lot of difficulty with my arrayList. I have got three buttons (in my jPanelBottom page) and when I click on the Start Button, every action i do from then on in (Selecting options from a menu or moving the jSlider) is supposed to be recorded. One I click the Stop button, it is supposed to stop recording and once I click on the Play button, every action I have done is supposed to be output to the screen. I have no idea how to do this.
I will attach some of my classes so you are able to see.
Here is my JPanelBottom page that contains everything ~I have created and my change event (for the jSlider)
public class jPanelBottom extends javax.swing.JPanel {
private JTextField jtfBoundaryLength, jtfArea;
private JSlider jsShapes;
private JLabel jLabelBoundaryLength, jLabelArea, jLabelSlider;
private JButton jbStart, jbStop, jbPlay;
//private JPanel jpBottom;
public jPanelBottom() {
initComponents();
//JSlider jsShapes = new JSlider();
jsShapes = new javax.swing.JSlider();
jsShapes.setMajorTickSpacing(10);
jsShapes.setPaintLabels(true);
jsShapes.setPaintTicks(true);
jsShapes.setSize(300, 100);
this.add(jsShapes);
jsShapes.addChangeListener(new event());
jtfBoundaryLength = new JTextField();
jtfBoundaryLength.setSize(100, 25);
jtfBoundaryLength.setLocation(550, 30);
this.add(jtfBoundaryLength);
jLabelBoundaryLength = new JLabel();
jLabelBoundaryLength.setText("Boundary Length: ");
jLabelBoundaryLength.setSize(130, 25);
jLabelBoundaryLength.setLocation(400, 30);
this.add(jLabelBoundaryLength);
jtfArea = new JTextField();
jtfArea.setSize(100, 25);
jtfArea.setLocation(550, 60);
this.add(jtfArea);
jLabelArea = new JLabel();
jLabelArea.setText("Area: ");
jLabelArea.setSize(100, 25);
jLabelArea.setLocation(400, 60);
this.add(jLabelArea);
jLabelSlider = new JLabel();
jLabelSlider.setText("Select the size please");
jLabelSlider.setSize(150, 150);
jLabelSlider.setLocation(85, 30);
this.add(jLabelSlider);
jbStart = new JButton();
jbStart.setText("Start");
jbStart.setSize(80, 25);
jbStart.setLocation(400, 95);
this.add(jbStart);
jbStop = new JButton();
jbStop.setText("Stop");
jbStop.setSize(80, 25);
jbStop.setLocation(500, 95);
this.add(jbStop);
jbPlay = new JButton();
jbPlay.setText("Play");
jbPlay.setSize(80, 25);
jbPlay.setLocation(600, 95);
this.add(jbPlay);
}
public class event implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
try {
if (MyFrame.shape1 == null) {
jtfBoundaryLength.setText("shape not set");
} else {
DecimalFormat g = new DecimalFormat("0.0");
jtfBoundaryLength.setText("" + g.format(MyFrame.shape1.getBoundaryLength(jsShapes.getValue())));
jtfArea.setText("" + g.format(MyFrame.shape1.getArea(jsShapes.getValue())));
}
MyFrame.shape1.setSliderValue(jsShapes.getValue());
} catch (Throwable ex) {}
}
}
public int getSliderValue() {
return this.jsShapes.getValue();
}
public void actionPerformed(ActionEvent e) {
System.out.println(MyFrame.shape1.getArrayList());
}
}
Here is my code for the Shapes page in which I create my ArrayList
public abstract class Shapes {
ArrayList<String> arrayList = new ArrayList();
protected double boundaryLength;
protected double area;
private int sliderValue;
public int getSliderValue() {
return sliderValue;
}
public void setSliderValue(int sliderValue) {
this.sliderValue = sliderValue;
}
public double getBoundaryLength(double boundaryLength)
{
return boundaryLength;
}
public double getArea(double area)
{
return area;
}
public ArrayList<String> getArrayList() {
return arrayList;
}
public void setArrayList(ArrayList arrayList) {
this.arrayList = arrayList;
}
}
Here is my MyFrame page which is where the menu is created. I have three options from the menu (Triangle, Circle and Square).
public class MyFrame extends javax.swing.JFrame implements ActionListener, ChangeListener {
public static Shapes shape1;
private JMenuItem Square;
private JMenuItem Triangle;
private JMenuItem Circle;
private MyControlPanel controlPanelShapes;
private jPanelTop d1 = new jPanelTop();
private jPanelBottom d2 = new jPanelBottom();
public MyFrame() {
initComponents();
controlPanelShapes = new MyControlPanel();
controlPanelShapes.setSize(1000, 1000);
controlPanelShapes.setLocation(0, 20);
add(controlPanelShapes);
d1.setSize(550, 230);
d1.setVisible(true);
this.add(d1);
JMenuBar jBarShape = new JMenuBar();
JMenu Shape = new JMenu();
Shape.setText("Shape");
Square = new JMenuItem();
Square.setText("Square");
Shape.add(Square);
Square.addActionListener(this);
Triangle = new JMenuItem();
Triangle.setText("Triangle");
Shape.add(Triangle);
Triangle.addActionListener(this);
Circle = new JMenuItem();
Circle.setText("Circle");
Shape.add(Circle);
Circle.addActionListener(this);
jBarShape.add(Shape);
setJMenuBar(jBarShape);
}
#Override
public void stateChanged(ChangeEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Circle) {
shape1 = new Circle();
d1.setCircle(true, false);
shape1.setSliderValue(d2.getSliderValue());
System.out.println(MyFrame.shape1.getArrayList());
} else if (e.getSource() == Triangle) {
shape1 = new Triangle();
d1.setTriangle(true, false);
shape1.setSliderValue(d2.getSliderValue());
System.out.println(MyFrame.shape1.getArrayList());
} else if (e.getSource() == Square) {
shape1 = new Square();
d1.setSquare(true, false);
shape1.setSliderValue(d2.getSliderValue());
System.out.println(MyFrame.shape1.getArrayList());
}
}
}
Basically when I click the play button, any time I click on a menu option or move the slider, it is supposed to be recorded and when I click Stop it stops recording. When I click Play it outputs it to the screen. I am sure it is fairly simple I just have no idea and I have been trying to get it to work for ages!
Thank You in advance for any help, it is extremely appreciated!
Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}