Inheritance, class types, and possibly some more where that came from

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 1030 Views - Last Post: 27 January 2013 - 06:32 AM Rate Topic: -----

#1 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Inheritance, class types, and possibly some more where that came from

Posted 09 January 2013 - 02:10 AM

Hello Java programmers! I have this project that I am planning where I am to make a math reflexes game. I was told (in a dead thread) that making a class for the game itself, and then extending that class for however many JLabels I want to use, is a bad way to go. I was wondering why. I think I know some of the reason why (everything would be public, and a public class is probably equivalent to a struct in C++, with functions), but then I thought classes were secure as they have private data members by default. Forgive me as I am dominant in C++, but know just about enough of languages like this one to adapt. Speaking of which, I was wondering if you could make a declaration of a function inside the class, and then define it outside the class.

P.S.: Sorry for the necropost; I am used to using cplusplus.com, where they just close dead topics. I thought this forum didn't close dead topics so as to consolidate the posts of the people needing help with the same/similar stuff. I know better now...

I was thinking that, as an alternative to inheritance, I could just use private classes declared within a public class. I think this would something like the concept of friend classes in C++. (In C++, a friend class has FULL ACCESS to the class that declared it a friend.)

Is This A Good Question/Topic? 0
  • +

Replies To: Inheritance, class types, and possibly some more where that came from

#2 raghav.naganathan  Icon User is offline

  • Perfectly Squared ;)
  • member icon

Reputation: 408
  • View blog
  • Posts: 1,440
  • Joined: 14-September 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 09 January 2013 - 02:19 AM

Well, first of all, what do you mean by a math reflexes game?

Quote

Speaking of which, I was wondering if you could make a declaration of a function inside the class, and then define it outside the class.


Well,unfortunately not...you need to note here is that there is no scope resolution operator in Java...the dot(.) is used for everything...now the question I have to ask you is 'why do you want to do the definition of the function outside the class?'

Edit: Added 'quote' tags.

regards,
Raghav

This post has been edited by raghav.naganathan: 09 January 2013 - 02:25 AM

Was This Post Helpful? 0
  • +
  • -

#3 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 09 January 2013 - 08:03 AM

View Postraghav.naganathan, on 09 January 2013 - 02:19 AM, said:

Well, first of all, what do you mean by a math reflexes game?


A math reflexes game is a game where you have to solve arithmetic problems as fast as you can.

Quote

now the question I have to ask you is 'why do you want to do the definition of the function outside the class?'


It would allow me to define a basic structure inside the class, and then use type theclass::some_function_or_private_class to define what that function should do outside the class. This way, the code is much easier to maintain, and therefore easier to write.

Aside from that, I have other questions (I mentioned them in my last post). One of them would be why would extending a class for the whole game be a bad idea? Is it strictly because of what I have mentioned in the first post (security issue)?

This post has been edited by IceHot: 09 January 2013 - 08:37 PM

Was This Post Helpful? 0
  • +
  • -

#4 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 10 January 2013 - 10:51 AM

I see that declaring the two windows as separate classes, and having one class call the other is a feasible option. (Kinda like friend classes in C++, except everything might be public.)

Also, I was wanting to know if you could make an array of JRadioButtons with something like:
JRadioButton[] buttonarray;
//some other lines of code
buttonarray = new JRadioButton[5];
for (int x = 0; x < buttonarray.length(); x++)
{
	buttonarray[x].setText("option "+(char)(65+x));
	if (x == 0)
	{
		buttonarray[x].setSelected(true);
	}	//end if
}	//end for



Note: The
"option "+(char)(65+x)
was just for arbitrary purposes. It isn't what I intend to set the string to. (It is a mere habit I learned from C++.

I am asking this because I have tried to implement this idea and it is producing something rather unexpected: only the very last button appears in the JFrame! I post full code (of the class whose methods I am calling):
import javax.swing.*;


public class UserPrompt 
{
	JFrame promptwindow;
	JLabel information;
	String description; //This will be the description of the game
	JRadioButton[] difficulties;
	final String[] buttonnames = {"Elementary School", "Middle School", "Big Adder", 
				"Divide and Conquer", "Human Calculator"};
	ButtonGroup selection;
	public UserPrompt() 
	{
		promptwindow = new JFrame("Mental Math Gym");
		//This pop-up will have the information about the game.
		description = "This game will hone your mental math skills by having you "+
		"solve arithmetic problems.\nThis game has five difficulties, ranging from "+
		"the most elementary arithmetic problems ever\n to the hardest problems you"+
		" have ever had to solve in your head.\nThe object of this game is to solve"+
		" them as quickly as you can.";
		JOptionPane.showMessageDialog(promptwindow,description, "Game Description", 
				JOptionPane.INFORMATION_MESSAGE);
		//telling the user to choose the difficulty
		information = new JLabel("Choose your difficulty:");
		information.setVerticalAlignment(SwingConstants.NORTH);
		information.setHorizontalAlignment(SwingConstants.CENTER);
		//giving them options to choose
		difficulties = new JRadioButton[5];
		selection = new ButtonGroup();
		for (int x = 0; x < 5; x++)
		{
			difficulties[x] = new JRadioButton(buttonnames[x]);
			difficulties[x].setHorizontalAlignment(SwingConstants.LEFT);
		}	//end for
		difficulties[0].setSelected(true);
		promptwindow.add(information);
		for (int x = 0; x < 5; x++)
		{
			promptwindow.add(difficulties[x]);
			selection.add(difficulties[x]);
		}	//end for
		promptwindow.setSize(300, 300);
		promptwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		promptwindow.setVisible(true);
	}	//end default constructor

}	//end UserPrompt


This post has been edited by IceHot: 10 January 2013 - 10:00 PM

Was This Post Helpful? 0
  • +
  • -

#5 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 11 January 2013 - 05:55 AM

If you're adding components to your JFrame and only the last added component is appearing, it sounds like you need to do some research into Layouts and LayoutManagers.

Edit:
Almost forgot, I'm constantly reading this line in my book.

"Java is not C++"

If the Tutors are going to tell me this over and over again it must be pretty important.

I only have a few days of experimentation with C++ so I guess it doesn't really affect me, but if you have picked up a lot of habits in C++ then logically you're probably going to shoot yourself in the foot a lot in Java. Try to forget the habits.

This post has been edited by Flukeshot: 11 January 2013 - 06:03 AM

Was This Post Helpful? 1
  • +
  • -

#6 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 12 January 2013 - 07:22 PM

Oh, and I am trying to create a new Time object (for the purpose of tracking the person's time), and my IDE (Eclipse) is suggesting that I
import javax.swing.Time;
when I have already done
import javax.swing.*;
. I don't know if posting my class code will make things better, but I probably should.
import javax.swing.*;
import java.util.*;
import java.awt.BorderLayout;
import java.math.*;
import java.awt.*;

public class Game
{
	//data members should go here
	JFrame gamewindow;
	Container container;
	GridLayout gamegrid;
	JLabel problemlabel, statusindicator;
	JLabel[] emptylabels;
	JTextField useranswer;	//The user's answer
	JButton confirm;	//User presses this to confirm their answer.
	int difficultylevel, numOfProblems, typedanswer;
	final String[] operators = {"+","-","*","/"};
	int[] numbers;	//array of integers associated with the problem
	public Game()
	{
		//set default difficulty level
		difficultylevel = 0;
		//Just make a window here....
		gamewindow = new JFrame("Mental Math Workout");
		//set container to JFrame's content pane
		container = gamewindow.getContentPane();
		//make the grid 
		gamegrid = new GridLayout(3,3);
		//set JFrame's layout to the grid
		gamewindow.setLayout(gamegrid);
		//initializing and adding the empty labels
		emptylabels = new JLabel[3];
		for (int temp = 0; temp < 3; temp++)
		{
			emptylabels[temp] = new JLabel();
			gamewindow.add(emptylabels[temp]);
		}	//end for
		//add the problemlabel
		problemlabel = new JLabel("Some string");
		gamewindow.add(problemlabel, BorderLayout.WEST);
		//add the textfield
		useranswer = new JTextField();
		gamewindow.add(useranswer, BorderLayout.CENTER);
		//add the confirm button
		confirm = new JButton("Next");
		gamewindow.add(confirm, BorderLayout.EAST);
		//add the Success/Fail indication
		statusindicator = new JLabel("I don't know if you passed or failed");
		//add some time object
		Timer time = new Timer();
		gamewindow.add(statusindicator, BorderLayout.SOUTH);
		gamewindow.setSize(350,150);
		gamewindow.setVisible(true);
		gamewindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}	//end constructor
	public Game(int x)
	{
		//This parametric constructor will take in the difficulty
		difficultylevel = x;
		JOptionPane.showMessageDialog(gamewindow, "You chose " + difficultylevel);
	}	//end parametric constructor
}	//end Game



Eclipse, why should I have to do the same thing twice?
Was This Post Helpful? 0
  • +
  • -

#7 FallenG  Icon User is offline

  • New D.I.C Head

Reputation: 22
  • View blog
  • Posts: 44
  • Joined: 12-January 13

Re: Inheritance, class types, and possibly some more where that came from

Posted 12 January 2013 - 07:44 PM

View PostIceHot, on 12 January 2013 - 07:22 PM, said:

Oh, and I am trying to create a new Time object (for the purpose of tracking the person's time), and my IDE (Eclipse) is suggesting that I
import javax.swing.Time;
when I have already done
import javax.swing.*;
. I don't know if posting my class code will make things better, but I probably should.

Eclipse, why should I have to do the same thing twice?

Do you know what a Timer is? You keep saying "Time", but in your code you try to instantiate "Timer". Which is it? Because they both exist, and they are not the same thing.

What specifically does it say? There is no reason it would ask you to import javax.swing.Timer; if you have done import javax.swing.*;.

However, if I remember correctly, the only available constructor for Timer is Timer(int delay, ActionListener listener). Unless I am mistaken, you are going to get an error because you have not provided the required parameters.
Was This Post Helpful? 1
  • +
  • -

#8 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 13 January 2013 - 01:07 AM

Sorry, I made a syntax error: It should be Timer (how did I screw this one up?) It seems like the Timer would be the class to use because it has a way of starting and stopping. I guess I should have been more careful with my reading of my Java book. *smacks self in face* I guess the better way would be to use a while loop that would go until all questions have been answered, and just use a Time object to display the time that has elapsed since the game has been started. I guess this is the source of my discrepancy.

EDIT: getHours(), getMinutes(), getSeconds() is all deprecated. FFFFFFFUUUUUUUU

This post has been edited by IceHot: 13 January 2013 - 01:14 AM

Was This Post Helpful? 0
  • +
  • -

#9 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: Inheritance, class types, and possibly some more where that came from

Posted 13 January 2013 - 04:49 AM

While deprecated methods often create frustration and angst, they were usually deprecated for good reasons, often because a better/safer way of doing the same thing was realized.

A common way to time an event, whether user performance or program execution, is to sample the system time and compute the differences in the samples:
long start = System.currentTimeMillis();

// execute the timed event

long end = System.currentTimeMillis(); 

// calculate elapsed time in ms:
long elapsedTimeInMS = end - start;

Was This Post Helpful? 1
  • +
  • -

#10 FallenG  Icon User is offline

  • New D.I.C Head

Reputation: 22
  • View blog
  • Posts: 44
  • Joined: 12-January 13

Re: Inheritance, class types, and possibly some more where that came from

Posted 13 January 2013 - 05:07 AM

View PostIceHot, on 13 January 2013 - 08:07 AM, said:

Sorry, I made a syntax error: It should be Timer (how did I screw this one up?) It seems like the Timer would be the class to use because it has a way of starting and stopping. I guess I should have been more careful with my reading of my Java book. *smacks self in face* I guess the better way would be to use a while loop that would go until all questions have been answered, and just use a Time object to display the time that has elapsed since the game has been started. I guess this is the source of my discrepancy.

EDIT: getHours(), getMinutes(), getSeconds() is all deprecated. FFFFFFFUUUUUUUU

A Timer is used to call events at regular intervals. You are best off storing the start time at some logical point (such as class creation), and then using a Timer to update a JLabel periodically with the current elapsed time.

Something like (untested code):
class MyClass { 
	protected long startTime;
	protected Timer elapsedTimer;
	
	public MyClass { 
		// Set the start time
		startTime = System.currentTimeMillis();
		
		// Create Timer with 1 second interval
		// It calls TimerActionListener.actionPerformed() every second
		elapsedTimer = new Timer(1000, new TimerActionListener());
	}
	
	class TimerActionListener implements ActionListener {
		@Override
	    public void actionPerformed(ActionEvent arg0) {
			long nowTime = System.currentTimeMillis();
			long elapsedTime = nowTime - startTime;
			// Display this to user in a JLabel or something, and format it out of Milliseconds to Mins:Secs or whatever
	    }
	}
}

Was This Post Helpful? 1
  • +
  • -

#11 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 13 January 2013 - 06:14 AM

import java.util.*;

...

Calendar calendar = Calendar.getInstance();



This is the replacement(reason for deprecation) of the Date utility. You can get Second, Minute, Hour, Day, Month, Year and more besides: http://docs.oracle.c...l/Calendar.html

Edit(more info):
The calendar will receive data once per getInstance, so you will need to use a timer to update the calendar every second.
Calendar calendar = Calendar.getInstance();
int date = calendar.get(Calendar.DAY_OF_WEEK);
int year = calendar.get(Calendar.YEAR);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);


This post has been edited by Flukeshot: 13 January 2013 - 06:20 AM

Was This Post Helpful? 1
  • +
  • -

#12 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 14 January 2013 - 11:57 AM

I am also getting a null pointer exception when I try to access a final array. I could post code here, but it will probably not do much good.
import javax.swing.*;
import java.util.*;
import java.math.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;

public class Game implements ActionListener,KeyListener
{
	//data members should go here
	JFrame gamewindow;
	Container container;
	GridLayout gamegrid;
	JLabel problemlabel, statusindicator;
	JLabel[] emptylabels;
	JTextField useranswer;	//The user's answer
	JButton confirm;	//User presses this to confirm their answer.
	private int difficultylevel, numOfProblems, typedanswer;
	private final char[] operators = {'+', '-', '*', '/'};
	private int[] numbers;	//array of integers associated with the problem
	private int[] elapsedtime;
	private long executiontime, temp;
	private char operator;
	private String problem;
	Random randomNumbers;
	public Game()
	{
		//set default difficulty level
		difficultylevel = 0;
		//Just make a window here....
		gamewindow = new JFrame("Mental Math Workout");
		//set container to JFrame's content pane
		container = gamewindow.getContentPane();
		//make the grid 
		gamegrid = new GridLayout(3,3);
		//set JFrame's layout to the grid
		gamewindow.setLayout(gamegrid);
		//initializing and adding the empty labels
		emptylabels = new JLabel[3];
		for (int temp = 0; temp < 3; temp++)
		{
			emptylabels[temp] = new JLabel();
			gamewindow.add(emptylabels[temp]);
		}	//end for
		//add the problemlabel
		problemlabel = new JLabel("Some string");
		gamewindow.add(problemlabel, BorderLayout.WEST);
		//add the textfield
		useranswer = new JTextField();
		gamewindow.add(useranswer, BorderLayout.CENTER);
		//add the confirm button
		confirm = new JButton("Next");
		gamewindow.add(confirm, BorderLayout.EAST);
		//add the Success/Fail indication
		statusindicator = new JLabel("Success/Fail");
		//add some time object
		gamewindow.add(statusindicator, BorderLayout.SOUTH);
		//initializing the number container and the random number generator
		Random randomNumbers = new Random();
		numbers = new int[3];
		confirm.addActionListener(this);
		//add a key listener
		gamewindow.addKeyListener(this);
		gamewindow.setSize(350,150);
		gamewindow.setVisible(true);
		executiontime = System.currentTimeMillis();
		elapsedtime = new int[3];
		gamewindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}	//end constructor
	public void actionPerformed(ActionEvent event)
	{
		JOptionPane.showMessageDialog(gamewindow, "You clicked the button");
	}	//end actionPerformed
	public void keyTyped(KeyEvent event)
	{
		//Check if they have typed the ENTER key.
		if (event.getKeyCode() == KeyEvent.VK_ENTER)
		{
			JOptionPane.showMessageDialog(gamewindow, "You pressed ENTER");
		}	//end if
		else
		{
			JOptionPane.showMessageDialog(gamewindow, "You didn't press ENTER");
		}
	}	//end keyTyped
	//These two methods are for when the user presses some non-ASCII key. They won't
	//be triggered, but having them is what is shutting the text-editor/compiler up.
	public void keyPressed(KeyEvent arg0)
	{
		
	}	//end keyPressed
	@Override
	public void keyReleased(KeyEvent e)
	{
		
	}	//end keyReleased
	public void setdifficulty(int x)
	{
		//This parametric constructor will take in the difficulty
		difficultylevel = x;
		JOptionPane.showMessageDialog(gamewindow, "You chose " + difficultylevel);
	}	//end parametric constructor
	public void showtime(long currenttime)
	{
		//setting array of elapsedtime
		temp = executiontime;
		currenttime -= temp;
		elapsedtime[0] = (int)Math.floor(currenttime / 3600000);
		currenttime -= elapsedtime[0] * 3600000;
		elapsedtime[1] = (int)Math.floor(currenttime / 60000);
		currenttime -= elapsedtime[1] * 60000;
		elapsedtime[2] = (int)Math.floor(currenttime / 1000);
		for (int n = 0; n < 3; n++)
		{
			if (elapsedtime[n] < 10)
			{
				System.out.print("0"+elapsedtime[n]);
			}
			else System.out.print(elapsedtime[n]);
			if (n != 2)
			{
				System.out.print(':');
			}	//end if
		}	//end for
	}	//end showtime
	public void makeproblem()
	{
		//First, choose the terminal character for the problem
		operator = operators[randomNumbers.nextInt(4)];
		switch(difficultylevel)
		{
			case 1:
				//This mode is the easiest difficulty the player could ask for. All
				//they have to do is add, subtract, multiply and divide one-digit 
				//numbers.
				numbers[1] = randomNumbers.nextInt(10);
				if (operator == '/')
				{
					while ((numbers[0] != 0) && (numbers[0] % numbers[1] != 0))
					{
						numbers[0] = randomNumbers.nextInt(10*numbers[1]);
					}	//end while
				}	//end if
				break;
			case 2:
				//This mode is a little harder as they will now have to add and 
				//subtract two-digit integers.
				break;
			case 3:
				break;
			case 4:
				break;
			default:
				//The default difficulty level will be Human Calculator mode
				//On this difficulty, the user will be expected to multiply two-
				//digit integers, add/subtract four-digit integers, and divide
				//four-digit integers by two-digit integers. Due to the difficulty,
				//there will be less problems.
				break;
		}	//end switch
		//Depending on the difficulty level
			//choose the type of problems that the user could be expected to solve
			//choose the integer arguments that form that problem
		//create the problem and set the problemlabel's text to this problem
		problem = String.format("%d %c %d %c", numbers[0],operator,numbers[1],'=');
		problemlabel.setText(problem);
		//have the machine solve this problem
		switch (operator)
		{
			case '+':
				numbers[2] = numbers[0] + numbers[1];
				break;
			case '-':
				numbers[2] = numbers[0] - numbers[1];
				break;
			case '*':
				numbers[2] = numbers[0] - numbers[1];
				break;
			default:
				numbers[2] = numbers[0] / numbers[1];
				break;
		}	//end switch
		
		//check the user's response against the computer's answer
		//if the user is right
			//display "Correct" in green text in the statusindicator
		//otherwise
			//display "Wrong" in red text in the statusindicator
	}	//end makeproblem
	
	
}	//end Game


The program throws the exception when I try to access the operators[], but I have it explicitly declared as a final array.

EDIT: Problem solved. I accidentally declared it twice. Now I am wondering how to make it so that the player could "press the Next button with the ENTER key". I tried to implement it in my code, but to no avail.

This post has been edited by IceHot: 14 January 2013 - 02:25 PM

Was This Post Helpful? 0
  • +
  • -

#13 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 15 January 2013 - 03:24 AM

If it's a textfield you can add an actionlistener to it, pressing enter will cause the actionPerformed() method to be fired.
Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8342
  • View blog
  • Posts: 31,880
  • Joined: 06-March 08

Re: Inheritance, class types, and possibly some more where that came from

Posted 15 January 2013 - 10:48 AM

For a JButton to react to a <ENTER> key, that JButton requires the focus that it can get:
- if it is the only focusable component in that container
- if the user <TAB> to it
Was This Post Helpful? 1
  • +
  • -

#15 IceHot  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 220
  • Joined: 28-August 12

Re: Inheritance, class types, and possibly some more where that came from

Posted 15 January 2013 - 12:28 PM

Thanks, pbl! My basic code is working now!! By the way, I was wondering if you could call actionPerformed (ActionEvent) from keyReleased(keyEvent). The game should advance to the next problem if the user clicks the button or tabs over to it and presses ENTER.

EDIT: I also have a question as to whether or not you would NEED to extend JPanel to use paintComponent. For example, could I use:
import javax.swing.*;
import java.awt.*;

public class coloredTextTest 
{
	JFrame mainwindow;
	GridLayout grid;
	Container container;
	JPanel[] panels;
	public coloredTextTest() 
	{
		mainwindow = new JFrame("Colored Text Test");
		grid = new GridLayout(2,1);
		container = mainwindow.getContentPane();
		panels = new JPanel[2];
		for (JPanel panel : panels)
		{
			panel = new JPanel();
			mainwindow.add(panel);
		}	//end for
		Graphics g;
		panels[0].paintComponent(g)
		{
			//manipulate the first panel
		}
	}

	public static void main(String[] args) 
	{
		coloredTextTest();
		mainwindow.setSize(200,200);
		mainwindow.setVisible(true);
		mainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}


This post has been edited by IceHot: 15 January 2013 - 07:28 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2